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xgJ,EACFla,GAAM,CAAC19B,OAAQ,CAACjL,EAAG8pG,EAAWh5F,EAAGqxC,GAAc94C,YAC7Ci6L,EACFjyL,GAAK,CAACpG,OAAQ,CAAC8D,EAAG8zC,GAAOx5C,UAASqP,MAAO,CAACha,MAAO,aAC/C6hC,EACF8mH,GAAS,CAACp8I,OAAQ,CAACjL,EAAGsjM,EAAYxyL,EAAG/B,GAAI1F,YACvCk6L,EACFv3J,GAAI,CAAC/gC,OAAQ,CAAC8D,EAAGwxB,GAAMl3B,UAASqP,MAAO,CAACxX,KAAM,EAAG25B,UAAU,KAC/D9iB,EAAItX,KAAK8iM,GACTpoB,EAAc16K,KAAKqpG,GACnBqxE,EAAc16K,KAAKoiD,GACnBs4H,EAAc16K,KAAK6iM,GACnBnoB,EAAc16K,KAAK8/B,GACnB46I,EAAc16K,KAAK8iM,GAGrB,MAAMpjM,EAASq3L,GAAK,CAACvsL,OAAQ8M,EAAK1O,UAASqP,MAAO,CAACxX,KAAM,KAIzD,OAFAi6K,EAAc33K,SAAQkD,GAAK2C,EAAQk4J,8BAA8B76J,KAE1DvG,CACT,GCkHMqjM,GAAgC,CACpCxoB,GACAtZ,GACA0Z,GACAC,GACA9V,GACA+V,GACAE,GACAG,GACAE,GACAC,GACAE,GACAC,GACAC,GACAE,GACAC,GACAmD,GACAC,GACA9zE,GACAG,GACAivE,GACAiG,GACAa,GACAG,GACA7b,GACA8b,GACA1e,GACAoD,GACA0b,GACAzf,GACA0f,GACAc,GACAwB,GACAC,GACAQ,GACAU,GACAQ,GACAkB,GACAO,GACAC,GACAC,GACA8B,GACAO,GACAC,GACAC,GACAY,GACAC,GACAE,GACAC,GACAC,GACAW,GACAG,GACAG,GACAM,GACAtU,GACAlrE,GACA25D,GACAsmB,GACApmB,GACAsmB,GACApmB,GACAmqB,GACAI,GACAC,GACAtqB,GACAE,GACAyqB,GACAI,GACAC,GACAC,GACA/pB,GACAE,GACAjG,GACAowB,GACAvQ,GACAwQ,GACAC,GACAC,GACAxa,GACA5P,GACAE,GACAmqB,GACAhqB,GACAiqB,GACAE,GACAC,GACAE,GACAC,GACAM,GACAO,GACA/qB,GACAgrB,GACAC,GACA1iF,GACAG,GACA0iF,GACAM,GACAG,GACA3rB,GACA4rB,GACAK,GACAQ,GACAtsB,GACAI,GACAysB,GACAC,GACAC,GACAzsB,GACA8sB,GACAI,GACAG,GACAC,GACAE,GACA9e,GACAjO,GACAgtB,GACAO,GACAK,GACAE,GACA71B,GACA+qB,GACA+K,GACA7f,GACAC,GACAG,GACA0f,GACAwB,GACA2B,GACAI,GACAc,GACAE,GACAM,GACA/rB,GACAgsB,GACAE,GACAG,GACAI,GACAnsB,GACAosB,GACAC,GACAC,GACA7rB,GACAyjB,GACAwI,GACAC,GACAO,GACAE,GACAC,GACAG,GACAC,GACAC,GACAnrB,GACAqrB,GACAnrB,GACAE,GACAmrB,GACAC,GACAG,GACAC,GACAC,GACAjpB,GACA2V,GACAuT,GR9UsC,CACtCthM,WAAY0lF,GACZ/7E,YAAa,MACb4Q,WAAYqnB,IQ6UZ2/J,GACAG,GACAC,GACAC,GACAn2B,GACAq4B,GACAC,GACAG,GACA7L,IAGF,IAAK,MAAMzxG,MAAgB29G,GACzBl+G,GAAeO,IChWjB,MAAMlY,GAAmD,CAAC,EAEpD81H,GAA2C,CAC/Cl1J,OAAO,EACPm1J,WAAW,EACXC,oBAAoB,EACpBC,uBAAuB,EACvBlvJ,OAAO,EACPmvJ,SAAS,EACTC,8BAA8B,GAO1B,SAAUC,GACZC,EAAsBC,GACxBt2H,GAASq2H,GAAgBC,CAC3B,CAEM,SAAUC,GACZF,EACAG,GACF,KAAMH,KAAgBr2H,KAA6B,MAAhBw2H,EAAsB,CACvD,MAAMC,EAwCV,SACIJ,EACAG,GACF,GAAqB,IAAjBH,GAAuC,IAAjBA,EACxB,MAAM,IAAI9kM,MAAM,0DAElB,MAAMk2F,EACc,MAAhB+uG,EApBN,SAAsBH,GAGpB,GAAKt/L,KAAMC,QAAQ,c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,EAAK,qBAAsB55K,EAAYqiE,EAAapiE,IAGjB74C,UAASqP,MAAO,CAACja,MAAOk/B,KAE/D,IAAIx9B,EAAS4kG,EACb,GAAmB,MAAfoI,EAAqB,CACvBkoF,EAAU50L,KAAKskG,GACf,MAAMrhD,EAAOqvD,GAAoC5F,GACjDhtG,EAASqjD,GAAU,CAACv4C,OAAQ,CAAC8D,EAAG5O,GAASkJ,UAASqP,MAAO,CAACgrC,UAI5D,OADA2xI,EAAU7xL,SAAQkD,GAAK2C,EAAQk4J,8BAA8B76J,KACtDvG,CACT,GCmFMqjM,GAAgC,CACpCxoB,GACAtZ,GACA0Z,GACAC,GACA9V,GACA+V,GACAE,GACAG,GACAE,GACAC,GACAE,GACAC,GACAC,GACAE,GACAC,GACAmD,GACAC,GACA9zE,GACAG,GACAivE,GACAiG,GACAa,GACAG,GACA7b,GACA8b,GACA1e,GACAoD,GACA0b,GACAzf,GACA0f,GACAc,GACAwB,GACAC,GACAQ,GACAU,GACAQ,GACAm9C,GACA17C,GACAC,GACAC,GACA8B,GACAO,GACAC,GACAC,GACAY,GACAC,GACAE,GACAC,GACAC,GACAuB,GACAtU,GACAlrE,GACA25D,GACAsmB,GACApmB,GACAsmB,GACApmB,GACAmqB,GACAI,GACAC,GACAtqB,GACAE,GACAw+D,GACA/zC,GACAI,GACAC,GACAC,GACA/pB,GACAE,GACAjG,GACAowB,GACAvQ,GACAwQ,GACAC,GACAC,GACAxa,GACA5P,GACAE,GACAmqB,GACAhqB,GACAiqB,GACAE,GACAC,GACAE,GACAC,GACAM,GACAO,GACA/qB,GACAgrB,GACAC,GACA1iF,GACAG,GACA0iF,GACAM,GACAG,GACA3rB,GACA4rB,GACAK,GACAQ,GACAtsB,GACAI,GACAysB,GACAC,GACAC,GACAzsB,GACA8sB,GACAI,GACAG,GACAC,GACAE,GACA9e,GACAjO,GACAgtB,GACAO,GACAK,GACAE,GACA71B,GACA+qB,GACA+K,GACA7f,GACAC,GACAG,GACA0f,GACAwB,GACA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,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,MACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,QCxMEC,GAA0B,CAC5BC,UAAW,CACP7/Q,MAAO,YACP8/Q,YAAa,uBACb70U,KAAM,OACN80U,aAAc,OACd9oG,YAAY,GAEhB+oG,kBAAmB,CACfhgR,MAAO,oBACP8/Q,YAAa,+BACb70U,KAAM,OACN80U,aAAc,gBACd9oG,YAAY,GAEhBgpG,iBAAkB,CACdjgR,MAAO,mBACP8/Q,YAAa,+BACb70U,KAAM,WACN80U,aAAc,eACd9oG,YAAY,GAEhBgrB,MAAO,CACHjiM,M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ASq/P,EAAAA,GAAAA,KAACg5G,GAAQ,KAEpB,CACE1gZ,KAAM,sBACNqoC,SAASq/P,EAAAA,GAAAA,KAACy4G,GAAkB,KAE9B,CACEngZ,KAAM,SACNqoC,SAASq/P,EAAAA,GAAAA,KAACi5G,GAAK,M9hB0NVp0H,GAAa,CAClBxsR,SAAU,MAAAitN,QAAA,EAAAA,GAAMjtN,SAChB+sR,OAAMrI,GAAA,GACD,MAAAz3D,QAAA,EAAAA,GAAM8/D,OAAM,CACfI,oBAAoB,IAEtBrlL,QAASi8K,EAAqB,CAAE9hS,OAAQ,MAAAgrO,QAAA,EAAAA,GAAMhrO,SAC9CwrS,eAAe,MAAAxgE,QAAA,EAAAA,GAAMwgE,gBAAiB2V,KACtChd,6BACAy6H,GACA5+Z,OAAQ,MAAAgrO,QAAA,EAAAA,GAAMhrO,SACbgxP,cAfW,IACdmzC,GACAn5D,G8hBpNWg3E,EAAAA,WAAoBroS,SAASklZ,eAAe,SACpDp3K,QACHi+D,EAAAA,GAAAA,KAACvJ,EAAAA,WAAgB,CAAA/hP,UACfsrP,EAAAA,GAAAA,KAACtD,GAAc,CAACxgS,OAAQA,QAO5Bk9Y","sources":["../../tfjs-core/src/backends/backend.ts","../../tfjs-core/src/util_base.ts","../../tfjs-core/src/environment.ts","../../tfjs-core/src/global_util.ts","../../tfjs-core/src/kernel_names.ts","../../tfjs-core/src/kernel_registry.ts","../../tfjs-core/src/log.ts","../../tfjs-core/src/hash_util.ts","../../tfjs-core/src/util.ts","../../tfjs-core/src/profiler.ts","../../tfjs-core/src/tensor_format.ts","../../tfjs-core/src/tensor.ts","../../tfjs-core/src/types.ts","../../tfjs-core/src/tensor_util.ts","../../tfjs-core/src/engine.ts","../../tfjs-core/src/tape.ts","../../tfjs-core/src/flags.ts","../../tfjs-core/src/tensor_util_env.ts","../../tfjs-core/src/device_util.ts","../../tfjs-core/src/ops/operation.ts","../../tfjs-core/src/ops/complex.ts","../../tfjs-core/src/ops/tensor_ops_util.ts","../../tfjs-core/src/ops/tensor.ts","../../tfjs-core/src/io/types.ts","../../tfjs-core/src/io/io_utils.ts","../../tfjs-core/src/io/router_registry.ts","../../tfjs-core/src/io/indexed_db.ts","../../tfjs-core/src/io/local_storage.ts","../../tfjs-core/src/io/model_management.ts","../../tfjs-core/src/platforms/platform_browser.ts","../../tfjs-core/src/platforms/platform_node.ts","../../tfjs-core/src/ops/buffer.ts","../../tfjs-core/src/ops/cast.ts","../../tfjs-core/src/ops/clone.ts","../../tfjs-core/src/ops/print.ts","../../tfjs-core/src/base_side_effects.ts","../../tfjs-core/src/io/browser_files.ts","../../tfjs-core/src/io/progress.ts","../../tfjs-core/src/io/weights_loader.ts","../../tfjs-core/src/io/http.ts","../../tfjs-core/src/io/passthrough.ts","../../tfjs-core/src/ops/abs.ts","../../tfjs-core/src/ops/acos.ts","../../tfjs-core/src/ops/acosh.ts","../../tfjs-core/src/ops/add.ts","../../tfjs-core/src/ops/add_n.ts","../../tfjs-core/src/ops/all.ts","../../tfjs-core/src/ops/any.ts","../../tfjs-core/src/ops/arg_max.ts","../../tfjs-core/src/ops/arg_min.ts","../../tfjs-core/src/ops/asin.ts","../../tfjs-core/src/ops/asinh.ts","../../tfjs-core/src/ops/atan.ts","../../tfjs-core/src/ops/atan2.ts","../../tfjs-core/src/ops/atanh.ts","../../tfjs-core/src/ops/conv_util.ts","../../tfjs-core/src/ops/reshape.ts","../../tfjs-core/src/ops/avg_pool.ts","../../tfjs-core/src/ops/avg_pool_3d.ts","../../tfjs-core/src/ops/concat.ts","../../tfjs-core/src/ops/mat_mul.ts","../../tfjs-core/src/ops/mul.ts","../../tfjs-core/src/ops/sigmoid.ts","../../tfjs-core/src/ops/slice.ts","../../tfjs-core/src/ops/tanh.ts","../../tfjs-core/src/ops/basic_lstm_cell.ts","../../tfjs-core/src/ops/batch_to_space_nd.ts","../../tfjs-core/src/ops/batchnorm.ts","../../tfjs-core/src/ops/batchnorm_util.ts","../../tfjs-core/src/ops/batchnorm2d.ts","../../tfjs-core/src/ops/batchnorm3d.ts","../../tfjs-core/src/ops/batchnorm4d.ts","../../tfjs-core/src/ops/bincount.ts","../../tfjs-core/src/ops/broadcast_args.ts","../../tfjs-core/src/ops/broadcast_to.ts","../../tfjs-core/src/ops/ceil.ts","../../tfjs-core/src/ops/fill.ts","../../tfjs-core/src/ops/clip_by_value.ts","../../tfjs-core/src/ops/concat_1d.ts","../../tfjs-core/src/ops/concat_2d.ts","../../tfjs-core/src/ops/concat_3d.ts","../../tfjs-core/src/ops/concat_4d.ts","../../tfjs-core/src/ops/conv2d.ts","../../tfjs-core/src/ops/conv1d.ts","../../tfjs-core/src/ops/conv2d_backprop_input.ts","../../tfjs-core/src/ops/conv2d_transpose.ts","../../tfjs-core/src/ops/conv3d.ts","../../tfjs-core/src/ops/conv3d_backprop_input.ts","../../tfjs-core/src/ops/conv3d_transpose.ts","../../tfjs-core/src/ops/cos.ts","../../tfjs-core/src/ops/cosh.ts","../../tfjs-core/src/ops/cumprod.ts","../../tfjs-core/src/ops/cumsum.ts","../../tfjs-core/src/ops/dense_bincount.ts","../../tfjs-core/src/ops/depth_to_space.ts","../../tfjs-core/src/ops/depthwise_conv2d.ts","../../tfjs-core/src/ops/diag.ts","../../tfjs-core/src/ops/dilation2d.ts","../../tfjs-core/src/ops/floorDiv.ts","../../tfjs-core/src/ops/div.ts","../../tfjs-core/src/ops/broadcast_util.ts","../../tfjs-core/src/ops/equal.ts","../../tfjs-core/src/ops/where.ts","../../tfjs-core/src/ops/zeros_like.ts","../../tfjs-core/src/ops/div_no_nan.ts","../../tfjs-core/src/ops/dot.ts","../../tfjs-core/src/ops/einsum.ts","../../tfjs-core/src/ops/elu.ts","../../tfjs-core/src/ops/erf.ts","../../tfjs-core/src/ops/axis_util.ts","../../tfjs-core/src/ops/max.ts","../../tfjs-core/src/ops/min.ts","../../tfjs-core/src/ops/pow.ts","../../tfjs-core/src/ops/scalar.ts","../../tfjs-core/src/ops/sqrt.ts","../../tfjs-core/src/ops/square.ts","../../tfjs-core/src/ops/sum.ts","../../tfjs-core/src/ops/norm.ts","../../tfjs-core/src/ops/euclidean_norm.ts","../../tfjs-core/src/ops/exp.ts","../../tfjs-core/src/ops/expand_dims.ts","../../tfjs-core/src/ops/expm1.ts","../../tfjs-core/src/ops/tile.ts","../../tfjs-core/src/ops/eye.ts","../../tfjs-core/src/ops/floor.ts","../../tfjs-core/src/ops/gather.ts","../../tfjs-core/src/ops/greater.ts","../../tfjs-core/src/ops/greater_equal.ts","../../tfjs-core/src/ops/imag.ts","../../tfjs-core/src/ops/is_finite.ts","../../tfjs-core/src/ops/is_inf.ts","../../tfjs-core/src/ops/is_nan.ts","../../tfjs-core/src/ops/leaky_relu.ts","../../tfjs-core/src/ops/less.ts","../../tfjs-core/src/ops/less_equal.ts","../../tfjs-core/src/ops/linspace.ts","../../tfjs-core/src/ops/local_response_normalization.ts","../../tfjs-core/src/ops/log.ts","../../tfjs-core/src/ops/log1p.ts","../../tfjs-core/src/gradients.ts","../../tfjs-core/src/ops/neg.ts","../../tfjs-core/src/ops/softplus.ts","../../tfjs-core/src/ops/log_sigmoid.ts","../../tfjs-core/src/ops/sub.ts","../../tfjs-core/src/ops/log_softmax.ts","../../tfjs-core/src/ops/log_sum_exp.ts","../../tfjs-core/src/ops/logical_and.ts","../../tfjs-core/src/ops/logical_not.ts","../../tfjs-core/src/ops/logical_or.ts","../../tfjs-core/src/ops/logical_xor.ts","../../tfjs-core/src/ops/search_sorted.ts","../../tfjs-core/src/ops/lower_bound.ts","../../tfjs-core/src/ops/max_pool.ts","../../tfjs-core/src/ops/max_pool_3d.ts","../../tfjs-core/src/ops/max_pool_with_argmax.ts","../../tfjs-core/src/ops/maximum.ts","../../tfjs-core/src/ops/mean.ts","../../tfjs-core/src/ops/zeros.ts","../../tfjs-core/src/ops/ones.ts","../../tfjs-core/src/ops/meshgrid.ts","../../tfjs-core/src/ops/minimum.ts","../../tfjs-core/src/ops/mirror_pad.ts","../../tfjs-core/src/ops/mod.ts","../../tfjs-core/src/ops/moments.ts","../../tfjs-core/src/ops/multi_rnn_cell.ts","../../tfjs-core/src/ops/multinomial.ts","../../tfjs-core/src/ops/not_equal.ts","../../tfjs-core/src/ops/one_hot.ts","../../tfjs-core/src/ops/ones_like.ts","../../tfjs-core/src/ops/outer_product.ts","../../tfjs-core/src/ops/pad.ts","../../tfjs-core/src/ops/pad1d.ts","../../tfjs-core/src/ops/pad2d.ts","../../tfjs-core/src/ops/pad3d.ts","../../tfjs-core/src/ops/pad4d.ts","../../tfjs-core/src/ops/space_to_batch_nd.ts","../../tfjs-core/src/ops/pool.ts","../../tfjs-core/src/ops/prelu.ts","../../tfjs-core/src/ops/prod.ts","../../tfjs-core/src/ops/ragged_gather.ts","../../tfjs-core/src/ops/ragged_tensor_to_tensor.ts","../../tfjs-core/src/ops/rand.ts","../../tfjs-core/src/ops/rand_util.ts","../../tfjs-core/src/ops/random_gamma.ts","../../tfjs-core/src/ops/random_normal.ts","../../tfjs-core/src/ops/random_standard_normal.ts","../../tfjs-core/src/ops/random_uniform.ts","../../tfjs-core/src/ops/range.ts","../../tfjs-core/src/ops/real.ts","../../tfjs-core/src/ops/reciprocal.ts","../../tfjs-core/src/ops/relu.ts","../../tfjs-core/src/ops/relu6.ts","../../tfjs-core/src/ops/reverse.ts","../../tfjs-core/src/ops/reverse_1d.ts","../../tfjs-core/src/ops/reverse_2d.ts","../../tfjs-core/src/ops/reverse_3d.ts","../../tfjs-core/src/ops/reverse_4d.ts","../../tfjs-core/src/ops/round.ts","../../tfjs-core/src/ops/rsqrt.ts","../../tfjs-core/src/ops/selu.ts","../../tfjs-core/src/ops/separable_conv2d.ts","../../tfjs-core/src/ops/setdiff1d_async.ts","../../tfjs-core/src/ops/sign.ts","../../tfjs-core/src/ops/sin.ts","../../tfjs-core/src/ops/sinh.ts","../../tfjs-core/src/ops/slice1d.ts","../../tfjs-core/src/ops/slice2d.ts","../../tfjs-core/src/ops/slice3d.ts","../../tfjs-core/src/ops/slice4d.ts","../../tfjs-core/src/ops/softmax.ts","../../tfjs-core/src/ops/spectral/fft.ts","../../tfjs-core/src/ops/spectral/ifft.ts","../../tfjs-core/src/ops/spectral/irfft.ts","../../tfjs-core/src/ops/split.ts","../../tfjs-core/src/ops/spectral/rfft.ts","../../tfjs-core/src/ops/squared_difference.ts","../../tfjs-core/src/ops/squeeze.ts","../../tfjs-core/src/ops/stack.ts","../../tfjs-core/src/ops/step.ts","../../tfjs-core/src/ops/strided_slice.ts","../../tfjs-core/src/ops/tan.ts","../../tfjs-core/src/ops/tensor1d.ts","../../tfjs-core/src/ops/tensor2d.ts","../../tfjs-core/src/ops/tensor3d.ts","../../tfjs-core/src/ops/tensor4d.ts","../../tfjs-core/src/ops/tensor5d.ts","../../tfjs-core/src/ops/tensor6d.ts","../../tfjs-core/src/ops/topk.ts","../../tfjs-core/src/ops/truncated_normal.ts","../../tfjs-core/src/ops/unique.ts","../../tfjs-core/src/ops/unsorted_segment_sum.ts","../../tfjs-core/src/ops/unstack.ts","../../tfjs-core/src/ops/upper_bound.ts","../../tfjs-core/src/ops/variable.ts","../../tfjs-core/src/ops/where_async.ts","../../tfjs-core/src/backends/where_impl.ts","../../tfjs-core/src/ops/boolean_mask.ts","../../tfjs-core/src/globals.ts","../../tfjs-core/src/ops/transpose.ts","../../tfjs-core/src/ops/moving_average.ts","../../tfjs-core/src/ops/scatter_nd_util.ts","../../tfjs-core/src/ops/scatter_nd.ts","../../tfjs-core/src/ops/sparse_to_dense.ts","../../tfjs-core/src/ops/sparse_to_dense_util.ts","../../tfjs-core/src/ops/gather_nd.ts","../../tfjs-core/src/ops/dropout.ts","../../tfjs-core/src/ops/dropout_util.ts","../../tfjs-core/src/ops/signal_ops_util.ts","../../tfjs-core/src/ops/in_top_k.ts","../../tfjs-core/src/ops/conv2d_backprop_filter.ts","../../tfjs-core/src/ops/fused_util.ts","../../tfjs-core/src/ops/fused/conv2d.ts","../../tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts","../../tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts","../../tfjs-core/src/ops/fused/depthwise_conv2d.ts","../../tfjs-core/src/ops/fused/mat_mul.ts","../../tfjs-core/src/ops/signal/hamming_window.ts","../../tfjs-core/src/ops/signal/hann_window.ts","../../tfjs-core/src/ops/signal/frame.ts","../../tfjs-core/src/ops/signal/stft.ts","../../tfjs-core/src/ops/image/crop_and_resize.ts","../../tfjs-core/src/ops/image/flip_left_right.ts","../../tfjs-core/src/ops/image/grayscale_to_rgb.ts","../../tfjs-core/src/ops/image/rotate_with_offset.ts","../../tfjs-core/src/ops/nonmax_util.ts","../../tfjs-core/src/ops/image/non_max_suppression.ts","../../tfjs-core/src/backends/non_max_suppression_util.ts","../../tfjs-core/src/backends/non_max_suppression_impl.ts","../../tfjs-core/src/ops/image/non_max_suppression_async.ts","../../tfjs-core/src/ops/image/non_max_suppression_with_score.ts","../../tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts","../../tfjs-core/src/ops/image/non_max_suppression_padded.ts","../../tfjs-core/src/ops/image/non_max_suppression_padded_async.ts","../../tfjs-core/src/ops/image/resize_bilinear.ts","../../tfjs-core/src/ops/image/resize_nearest_neighbor.ts","../../tfjs-core/src/ops/image/threshold.ts","../../tfjs-core/src/ops/image/transform.ts","../../tfjs-core/src/ops/linalg/band_part.ts","../../tfjs-core/src/ops/linalg/gram_schmidt.ts","../../tfjs-core/src/ops/linalg/qr.ts","../../tfjs-core/src/ops/loss_ops_utils.ts","../../tfjs-core/src/ops/losses/compute_weighted_loss.ts","../../tfjs-core/src/ops/losses/absolute_difference.ts","../../tfjs-core/src/ops/losses/cosine_distance.ts","../../tfjs-core/src/ops/losses/hinge_loss.ts","../../tfjs-core/src/ops/losses/huber_loss.ts","../../tfjs-core/src/ops/losses/log_loss.ts","../../tfjs-core/src/ops/losses/mean_squared_error.ts","../../tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts","../../tfjs-core/src/ops/losses/softmax_cross_entropy.ts","../../tfjs-core/src/ops/sparse/sparse_fill_empty_rows.ts","../../tfjs-core/src/ops/sparse/sparse_reshape.ts","../../tfjs-core/src/ops/sparse/sparse_segment_mean.ts","../../tfjs-core/src/ops/sparse/sparse_segment_sum.ts","../../tfjs-core/src/ops/string/string_n_grams.ts","../../tfjs-core/src/ops/string/string_split.ts","../../tfjs-core/src/ops/string/string_to_hash_bucket_fast.ts","../../tfjs-core/src/ops/ops.ts","../../tfjs-converter/src/data/compiled_api.ts","../../tfjs-converter/src/flags.ts","../../tfjs-converter/src/operations/custom_op/register.ts","../../tfjs-converter/src/operations/executors/utils.ts","../../tfjs-converter/src/operations/op_list/arithmetic.ts","../../tfjs-converter/src/operations/op_list/basic_math.ts","../../tfjs-converter/src/operations/op_list/control.ts","../../tfjs-converter/src/operations/op_list/convolution.ts","../../tfjs-converter/src/operations/op_list/creation.ts","../../tfjs-converter/src/operations/op_list/dynamic.ts","../../tfjs-converter/src/operations/op_list/evaluation.ts","../../tfjs-converter/src/operations/op_list/graph.ts","../../tfjs-converter/src/operations/op_list/hash_table.ts","../../tfjs-converter/src/operations/op_list/image.ts","../../tfjs-converter/src/operations/op_list/logical.ts","../../tfjs-converter/src/operations/op_list/matrices.ts","../../tfjs-converter/src/operations/op_list/normalization.ts","../../tfjs-converter/src/operations/op_list/reduction.ts","../../tfjs-converter/src/operations/op_list/slice_join.ts","../../tfjs-converter/src/operations/op_list/sparse.ts","../../tfjs-converter/src/operations/op_list/spectral.ts","../../tfjs-converter/src/operations/op_list/string.ts","../../tfjs-converter/src/operations/op_list/transformation.ts","../../tfjs-converter/src/operations/operation_mapper.ts","../../tfjs-converter/src/operations/custom_op/node_value_impl.ts","../../tfjs-converter/src/executor/tensor_utils.ts","../../tfjs-converter/src/executor/tensor_array.ts","../../tfjs-converter/src/executor/tensor_list.ts","../../tfjs-converter/src/operations/executors/control_executor.ts","../../tfjs-converter/src/operations/executors/convolution_executor.ts","../../tfjs-converter/src/operations/executors/dynamic_executor.ts","../../tfjs-converter/src/executor/hash_table.ts","../../tfjs-converter/src/operations/operation_executor.ts","../../tfjs-converter/src/operations/executors/arithmetic_executor.ts","../../tfjs-converter/src/operations/executors/basic_math_executor.ts","../../tfjs-converter/src/operations/executors/creation_executor.ts","../../tfjs-converter/src/operations/executors/evaluation_executor.ts","../../tfjs-converter/src/operations/executors/image_executor.ts","../../tfjs-converter/src/operations/executors/graph_executor.ts","../../tfjs-converter/src/operations/executors/logical_executor.ts","../../tfjs-converter/src/operations/executors/matrices_executor.ts","../../tfjs-converter/src/operations/executors/normalization_executor.ts","../../tfjs-converter/src/operations/executors/reduction_executor.ts","../../tfjs-converter/src/operations/executors/slice_join_executor.ts","../../tfjs-converter/src/operations/executors/sparse_executor.ts","../../tfjs-converter/src/operations/executors/spectral_executor.ts","../../tfjs-converter/src/operations/executors/string_executor.ts","../../tfjs-converter/src/operations/executors/transformation_executor.ts","../../tfjs-converter/src/operations/executors/hash_table_executor.ts","../../tfjs-converter/src/executor/execution_context.ts","../../tfjs-converter/src/executor/model_analysis.ts","../../tfjs-converter/src/executor/graph_executor.ts","../../tfjs-converter/src/executor/resource_manager.ts","../../tfjs-converter/src/executor/graph_model.ts","../node_modules/@tensorflow-models/universal-sentence-encoder/dist/universal-sentence-encoder.esm.js","../node_modules/@tensorflow/tfjs-core/src/backends/backend.ts","../node_modules/@tensorflow/tfjs-core/src/util_base.ts","../node_modules/@tensorflow/tfjs-core/src/environment.ts","../node_modules/@tensorflow/tfjs-core/src/global_util.ts","../node_modules/@tensorflow/tfjs-core/src/kernel_names.ts","../node_modules/@tensorflow/tfjs-core/src/log.ts","../node_modules/@tensorflow/tfjs-core/src/kernel_registry.ts","../node_modules/@tensorflow/tfjs-core/src/platforms/is_typed_array_browser.ts","../node_modules/@tensorflow/tfjs-core/src/hash_util.ts","../node_modules/@tensorflow/tfjs-core/src/util.ts","../node_modules/@tensorflow/tfjs-core/src/profiler.ts","../node_modules/@tensorflow/tfjs-core/src/tensor_format.ts","../node_modules/@tensorflow/tfjs-core/src/tensor.ts","../node_modules/@tensorflow/tfjs-core/src/types.ts","../node_modules/@tensorflow/tfjs-core/src/tensor_util.ts","../node_modules/@tensorflow/tfjs-core/src/engine.ts","../node_modules/@tensorflow/tfjs-core/src/tape.ts","../node_modules/@tensorflow/tfjs-core/src/device_util.ts","../node_modules/@tensorflow/tfjs-core/src/flags.ts","../node_modules/@tensorflow/tfjs-core/src/tensor_util_env.ts","../node_modules/@tensorflow/tfjs-core/src/ops/operation.ts","../node_modules/@tensorflow/tfjs-core/src/ops/complex.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor_ops_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor.ts","../node_modules/@tensorflow/tfjs-core/src/io/types.ts","../node_modules/@tensorflow/tfjs-core/src/io/composite_array_buffer.ts","../node_modules/@tensorflow/tfjs-core/src/globals.ts","../node_modules/@tensorflow/tfjs-core/src/io/io_utils.ts","../node_modules/@tensorflow/tfjs-core/src/io/router_registry.ts","../node_modules/@tensorflow/tfjs-core/src/io/indexed_db.ts","../node_modules/@tensorflow/tfjs-core/src/io/local_storage.ts","../node_modules/@tensorflow/tfjs-core/src/io/model_management.ts","../node_modules/@tensorflow/tfjs-core/src/platforms/platform_browser.ts","../node_modules/@tensorflow/tfjs-core/src/platforms/platform_node.ts","../node_modules/@tensorflow/tfjs-core/src/ops/buffer.ts","../node_modules/@tensorflow/tfjs-core/src/ops/cast.ts","../node_modules/@tensorflow/tfjs-core/src/ops/clone.ts","../node_modules/@tensorflow/tfjs-core/src/ops/print.ts","../node_modules/@tensorflow/tfjs-core/src/base_side_effects.ts","../node_modules/@tensorflow/tfjs-core/src/ops/add.ts","../node_modules/@tensorflow/tfjs-core/src/ops/floorDiv.ts","../node_modules/@tensorflow/tfjs-core/src/ops/div.ts","../node_modules/@tensorflow/tfjs-core/src/ops/mul.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sqrt.ts","../node_modules/@tensorflow/tfjs-core/src/ops/square.ts","../node_modules/@tensorflow/tfjs-core/src/ops/zeros_like.ts","../node_modules/@tensorflow/tfjs-core/src/gradients.ts","../node_modules/@tensorflow/tfjs-core/src/ops/scalar.ts","../node_modules/@tensorflow/tfjs-core/src/serialization.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/adadelta_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/ops/fill.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/adagrad_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pow.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sub.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/adam_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/ops/abs.ts","../node_modules/@tensorflow/tfjs-core/src/ops/broadcast_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/maximum.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/adamax_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/sgd_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/momentum_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/rmsprop_optimizer.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/register_optimizers.ts","../node_modules/@tensorflow/tfjs-core/src/io/browser_files.ts","../node_modules/@tensorflow/tfjs-core/src/io/progress.ts","../node_modules/@tensorflow/tfjs-core/src/io/weights_loader.ts","../node_modules/@tensorflow/tfjs-core/src/io/http.ts","../node_modules/@tensorflow/tfjs-core/src/io/passthrough.ts","../node_modules/@tensorflow/tfjs-core/src/ops/mat_mul.ts","../node_modules/@tensorflow/tfjs-core/src/ops/one_hot.ts","../node_modules/@tensorflow/tfjs-core/src/ops/imag.ts","../node_modules/@tensorflow/tfjs-core/src/ops/neg.ts","../node_modules/@tensorflow/tfjs-core/src/ops/real.ts","../node_modules/@tensorflow/tfjs-core/src/ops/transpose.ts","../node_modules/@tensorflow/tfjs-core/src/ops/confusion_matrix.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/browser.ts","../node_modules/@tensorflow/tfjs-core/src/ops/gather_nd_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/scatter_nd_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/slice_util.ts","../node_modules/@tensorflow/tfjs-core/src/test_util.ts","../node_modules/@tensorflow/tfjs-core/src/version.ts","../node_modules/@tensorflow/tfjs-core/src/optimizers/optimizer_constructors.ts","../node_modules/@tensorflow/tfjs-core/src/ops/acos.ts","../node_modules/@tensorflow/tfjs-core/src/ops/acosh.ts","../node_modules/@tensorflow/tfjs-core/src/ops/add_n.ts","../node_modules/@tensorflow/tfjs-core/src/ops/all.ts","../node_modules/@tensorflow/tfjs-core/src/ops/any.ts","../node_modules/@tensorflow/tfjs-core/src/ops/arg_max.ts","../node_modules/@tensorflow/tfjs-core/src/ops/arg_min.ts","../node_modules/@tensorflow/tfjs-core/src/ops/asin.ts","../node_modules/@tensorflow/tfjs-core/src/ops/asinh.ts","../node_modules/@tensorflow/tfjs-core/src/ops/atan.ts","../node_modules/@tensorflow/tfjs-core/src/ops/atan2.ts","../node_modules/@tensorflow/tfjs-core/src/ops/atanh.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reshape.ts","../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool.ts","../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/concat.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sigmoid.ts","../node_modules/@tensorflow/tfjs-core/src/ops/slice.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tanh.ts","../node_modules/@tensorflow/tfjs-core/src/ops/basic_lstm_cell.ts","../node_modules/@tensorflow/tfjs-core/src/ops/batch_to_space_nd.ts","../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm.ts","../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm4d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/bincount.ts","../node_modules/@tensorflow/tfjs-core/src/ops/bitwise_and.ts","../node_modules/@tensorflow/tfjs-core/src/ops/broadcast_args.ts","../node_modules/@tensorflow/tfjs-core/src/ops/broadcast_to.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ceil.ts","../node_modules/@tensorflow/tfjs-core/src/ops/clip_by_value.ts","../node_modules/@tensorflow/tfjs-core/src/ops/concat_1d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/concat_2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/concat_3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/concat_4d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv1d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv2d_backprop_input.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv2d_transpose.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv3d_backprop_input.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv3d_transpose.ts","../node_modules/@tensorflow/tfjs-core/src/ops/cos.ts","../node_modules/@tensorflow/tfjs-core/src/ops/cosh.ts","../node_modules/@tensorflow/tfjs-core/src/ops/cumprod.ts","../node_modules/@tensorflow/tfjs-core/src/ops/cumsum.ts","../node_modules/@tensorflow/tfjs-core/src/ops/dense_bincount.ts","../node_modules/@tensorflow/tfjs-core/src/ops/depth_to_space.ts","../node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/diag.ts","../node_modules/@tensorflow/tfjs-core/src/ops/dilation2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/equal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/where.ts","../node_modules/@tensorflow/tfjs-core/src/ops/div_no_nan.ts","../node_modules/@tensorflow/tfjs-core/src/ops/dot.ts","../node_modules/@tensorflow/tfjs-core/src/ops/einsum.ts","../node_modules/@tensorflow/tfjs-core/src/ops/elu.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ensure_shape.ts","../node_modules/@tensorflow/tfjs-core/src/ops/erf.ts","../node_modules/@tensorflow/tfjs-core/src/ops/axis_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/max.ts","../node_modules/@tensorflow/tfjs-core/src/ops/min.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sum.ts","../node_modules/@tensorflow/tfjs-core/src/ops/norm.ts","../node_modules/@tensorflow/tfjs-core/src/ops/euclidean_norm.ts","../node_modules/@tensorflow/tfjs-core/src/ops/exp.ts","../node_modules/@tensorflow/tfjs-core/src/ops/expand_dims.ts","../node_modules/@tensorflow/tfjs-core/src/ops/expm1.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tile.ts","../node_modules/@tensorflow/tfjs-core/src/ops/eye.ts","../node_modules/@tensorflow/tfjs-core/src/ops/floor.ts","../node_modules/@tensorflow/tfjs-core/src/ops/gather.ts","../node_modules/@tensorflow/tfjs-core/src/ops/greater.ts","../node_modules/@tensorflow/tfjs-core/src/ops/greater_equal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/is_finite.ts","../node_modules/@tensorflow/tfjs-core/src/ops/is_inf.ts","../node_modules/@tensorflow/tfjs-core/src/ops/is_nan.ts","../node_modules/@tensorflow/tfjs-core/src/ops/leaky_relu.ts","../node_modules/@tensorflow/tfjs-core/src/ops/less.ts","../node_modules/@tensorflow/tfjs-core/src/ops/less_equal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/linspace.ts","../node_modules/@tensorflow/tfjs-core/src/ops/local_response_normalization.ts","../node_modules/@tensorflow/tfjs-core/src/ops/log.ts","../node_modules/@tensorflow/tfjs-core/src/ops/log1p.ts","../node_modules/@tensorflow/tfjs-core/src/ops/softplus.ts","../node_modules/@tensorflow/tfjs-core/src/ops/log_sigmoid.ts","../node_modules/@tensorflow/tfjs-core/src/ops/log_softmax.ts","../node_modules/@tensorflow/tfjs-core/src/ops/log_sum_exp.ts","../node_modules/@tensorflow/tfjs-core/src/ops/logical_and.ts","../node_modules/@tensorflow/tfjs-core/src/ops/logical_not.ts","../node_modules/@tensorflow/tfjs-core/src/ops/logical_or.ts","../node_modules/@tensorflow/tfjs-core/src/ops/logical_xor.ts","../node_modules/@tensorflow/tfjs-core/src/ops/search_sorted.ts","../node_modules/@tensorflow/tfjs-core/src/ops/lower_bound.ts","../node_modules/@tensorflow/tfjs-core/src/ops/max_pool.ts","../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_with_argmax.ts","../node_modules/@tensorflow/tfjs-core/src/ops/mean.ts","../node_modules/@tensorflow/tfjs-core/src/ops/zeros.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ones.ts","../node_modules/@tensorflow/tfjs-core/src/ops/meshgrid.ts","../node_modules/@tensorflow/tfjs-core/src/ops/minimum.ts","../node_modules/@tensorflow/tfjs-core/src/ops/mirror_pad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/mod.ts","../node_modules/@tensorflow/tfjs-core/src/ops/moments.ts","../node_modules/@tensorflow/tfjs-core/src/ops/multi_rnn_cell.ts","../node_modules/@tensorflow/tfjs-core/src/ops/multinomial.ts","../node_modules/@tensorflow/tfjs-core/src/ops/not_equal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ones_like.ts","../node_modules/@tensorflow/tfjs-core/src/ops/outer_product.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pad1d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pad2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pad3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pad4d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/space_to_batch_nd.ts","../node_modules/@tensorflow/tfjs-core/src/ops/pool.ts","../node_modules/@tensorflow/tfjs-core/src/ops/prelu.ts","../node_modules/@tensorflow/tfjs-core/src/ops/prod.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ragged_gather.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ragged_range.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ragged_tensor_to_tensor.ts","../node_modules/@tensorflow/tfjs-core/src/ops/rand.ts","../node_modules/@tensorflow/tfjs-core/src/ops/rand_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/random_gamma.ts","../node_modules/@tensorflow/tfjs-core/src/ops/random_normal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/random_standard_normal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/random_uniform.ts","../node_modules/@tensorflow/tfjs-core/src/ops/random_uniform_int.ts","../node_modules/@tensorflow/tfjs-core/src/ops/range.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reciprocal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/relu.ts","../node_modules/@tensorflow/tfjs-core/src/ops/relu6.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reverse.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reverse_1d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reverse_2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reverse_3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reverse_4d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/round.ts","../node_modules/@tensorflow/tfjs-core/src/ops/rsqrt.ts","../node_modules/@tensorflow/tfjs-core/src/ops/selu.ts","../node_modules/@tensorflow/tfjs-core/src/ops/separable_conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/setdiff1d_async.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sign.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sin.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sinh.ts","../node_modules/@tensorflow/tfjs-core/src/ops/slice1d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/slice2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/slice3d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/slice4d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/softmax.ts","../node_modules/@tensorflow/tfjs-core/src/ops/spectral/fft.ts","../node_modules/@tensorflow/tfjs-core/src/ops/spectral/ifft.ts","../node_modules/@tensorflow/tfjs-core/src/ops/spectral/irfft.ts","../node_modules/@tensorflow/tfjs-core/src/ops/split.ts","../node_modules/@tensorflow/tfjs-core/src/ops/spectral/rfft.ts","../node_modules/@tensorflow/tfjs-core/src/ops/squared_difference.ts","../node_modules/@tensorflow/tfjs-core/src/ops/squeeze.ts","../node_modules/@tensorflow/tfjs-core/src/ops/stack.ts","../node_modules/@tensorflow/tfjs-core/src/ops/step.ts","../node_modules/@tensorflow/tfjs-core/src/ops/strided_slice.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tan.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor1d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor4d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor5d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor6d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/tensor_scatter_update.ts","../node_modules/@tensorflow/tfjs-core/src/ops/topk.ts","../node_modules/@tensorflow/tfjs-core/src/ops/truncated_normal.ts","../node_modules/@tensorflow/tfjs-core/src/ops/unique.ts","../node_modules/@tensorflow/tfjs-core/src/ops/unsorted_segment_sum.ts","../node_modules/@tensorflow/tfjs-core/src/ops/unstack.ts","../node_modules/@tensorflow/tfjs-core/src/ops/upper_bound.ts","../node_modules/@tensorflow/tfjs-core/src/ops/variable.ts","../node_modules/@tensorflow/tfjs-core/src/backends/where_impl.ts","../node_modules/@tensorflow/tfjs-core/src/ops/where_async.ts","../node_modules/@tensorflow/tfjs-core/src/ops/boolean_mask.ts","../node_modules/@tensorflow/tfjs-core/src/ops/moving_average.ts","../node_modules/@tensorflow/tfjs-core/src/ops/scatter_nd.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse_to_dense.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse_to_dense_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/gather_nd.ts","../node_modules/@tensorflow/tfjs-core/src/ops/dropout.ts","../node_modules/@tensorflow/tfjs-core/src/ops/dropout_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/signal_ops_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/in_top_k.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv2d_backprop_filter.ts","../node_modules/@tensorflow/tfjs-core/src/ops/fused_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/fused/conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts","../node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts","../node_modules/@tensorflow/tfjs-core/src/ops/fused/depthwise_conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/ops/fused/mat_mul.ts","../node_modules/@tensorflow/tfjs-core/src/ops/signal/hamming_window.ts","../node_modules/@tensorflow/tfjs-core/src/ops/signal/hann_window.ts","../node_modules/@tensorflow/tfjs-core/src/ops/signal/frame.ts","../node_modules/@tensorflow/tfjs-core/src/ops/signal/stft.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/crop_and_resize.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/flip_left_right.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/grayscale_to_rgb.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/rgb_to_grayscale.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/rotate_with_offset.ts","../node_modules/@tensorflow/tfjs-core/src/ops/nonmax_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression.ts","../node_modules/@tensorflow/tfjs-core/src/backends/non_max_suppression_util.ts","../node_modules/@tensorflow/tfjs-core/src/backends/non_max_suppression_impl.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_async.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_with_score.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_padded.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_padded_async.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/resize_bilinear.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/resize_nearest_neighbor.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/threshold.ts","../node_modules/@tensorflow/tfjs-core/src/ops/image/transform.ts","../node_modules/@tensorflow/tfjs-core/src/ops/linalg/band_part.ts","../node_modules/@tensorflow/tfjs-core/src/ops/linalg/gram_schmidt.ts","../node_modules/@tensorflow/tfjs-core/src/ops/linalg/qr.ts","../node_modules/@tensorflow/tfjs-core/src/ops/loss_ops_utils.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/compute_weighted_loss.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/absolute_difference.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/cosine_distance.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/hinge_loss.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/huber_loss.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/log_loss.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/mean_squared_error.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts","../node_modules/@tensorflow/tfjs-core/src/ops/losses/softmax_cross_entropy.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_fill_empty_rows.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_reshape.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_segment_mean.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_segment_sum.ts","../node_modules/@tensorflow/tfjs-core/src/ops/string/string_n_grams.ts","../node_modules/@tensorflow/tfjs-core/src/ops/string/string_split.ts","../node_modules/@tensorflow/tfjs-core/src/ops/string/string_to_hash_bucket_fast.ts","../node_modules/@tensorflow/tfjs-core/src/ops/string/static_regex_replace.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ops.ts","../node_modules/@tensorflow/tfjs-core/src/train.ts","../node_modules/@tensorflow/tfjs-core/src/browser_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/concat_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/ragged_to_dense_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/reduce_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/rotate_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/array_ops_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/selu_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/erf_util.ts","../node_modules/@tensorflow/tfjs-core/src/backends/complex_util.ts","../node_modules/@tensorflow/tfjs-core/src/backends/einsum_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/split_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_fill_empty_rows_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_reshape_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_segment_reduction_util.ts","../node_modules/@tensorflow/tfjs-core/src/ops/segment_util.ts","../node_modules/@tensorflow/tfjs-core/src/backends/backend_util.ts","../node_modules/@tensorflow/tfjs-core/src/index.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Abs_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Acos_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Acosh_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Add_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/AddN_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ArgMax_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ArgMin_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Asin_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Asinh_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Atan2_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Atan_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Atanh_grad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_3d_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/AvgPool3D_grad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/AvgPool_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/BatchMatMul_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/BatchToSpaceND_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/BroadcastTo_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Cast_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Ceil_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ClipByValue_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ComplexAbs_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Concat_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Conv2D_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Conv2DBackpropInput_grad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/conv3d_backprop_filter.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Conv3D_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Cos_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Cosh_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Cumsum_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/DepthwiseConv2dNative_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Dilation2D_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Elu_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Erf_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Exp_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ExpandDims_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Expm1_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Floor_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/FloorDiv_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/FusedBatchNorm_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/GatherV2_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/GreaterEqual_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Identity_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/IsFinite_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/IsInf_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/IsNan_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/LeakyRelu_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Log1p_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Log_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/LogSoftmax_grad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/local_response_normalization_backprop.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/LRN_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/min_max_grad_util.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Max_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Maximum_grad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_3d_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/MaxPool3D_grad.ts","../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/MaxPool_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/MirrorPad_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/PadV2_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Pow_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Prod_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Selu_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/SpaceToBatchND_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/SplitV_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ZerosLike_grad.ts","../node_modules/@tensorflow/tfjs-core/src/register_all_gradients.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/RealDiv_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Mean_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Min_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Minimum_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Mod_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Multiply_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Neg_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/OneHot_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/OnesLike_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Pack_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Prelu_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Reciprocal_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Relu6_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Relu_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Reshape_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ResizeBilinear_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/ResizeNearestNeighbor_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Reverse_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Round_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Rsqrt_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Select_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sigmoid_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sign_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sin_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sinh_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Slice_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Softmax_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Softplus_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sqrt_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/SquaredDifference_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Square_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Step_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sub_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Sum_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Tan_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Tanh_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Tile_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Transpose_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/Unpack_grad.ts","../node_modules/@tensorflow/tfjs-core/src/gradients/UnsortedSegmentSum_grad.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/abs.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/acos.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/acosh.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/add.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/all.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/any.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/arg_max.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/arg_min.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as_scalar.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as_type.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as1d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as2d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as3d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as4d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as5d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/asin.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/asinh.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/atan.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/atan2.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/atanh.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/avg_pool.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/batch_to_space_nd.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/batchnorm.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/broadcast_to.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cast.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/ceil.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/clip_by_value.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/concat.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/conv1d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/conv2d_transpose.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cos.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cosh.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cumprod.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cumsum.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/depth_to_space.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/depthwise_conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/dilation2d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/div_no_nan.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/div.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/dot.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/elu.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/equal.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/erf.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/euclidean_norm.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/exp.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/expand_dims.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/expm1.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/fft.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/flatten.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/floor.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/floorDiv.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/gather.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/greater_equal.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/greater.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/ifft.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/irfft.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/is_finite.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/is_inf.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/is_nan.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/leaky_relu.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/less_equal.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/less.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/local_response_normalization.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log_sigmoid.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log_softmax.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log_sum_exp.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log1p.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_and.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_not.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_or.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_xor.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mat_mul.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/max_pool.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/max.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/maximum.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mean.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/min.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/minimum.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mirror_pad.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mod.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mul.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/neg.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/norm.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/not_equal.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/one_hot.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/ones_like.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pad.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pool.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pow.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/prelu.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/prod.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reciprocal.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/relu.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/relu6.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reshape_as.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reshape.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/resize_bilinear.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/resize_nearest_neighbor.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reverse.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/rfft.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/round.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/rsqrt.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/selu.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/separable_conv2d.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sigmoid.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sign.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sin.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sinh.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/slice.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/softmax.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/softplus.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/space_to_batch_nd.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/split.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sqrt.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/square.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/squared_difference.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/squeeze.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/stack.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/step.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/strided_slice.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sub.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sum.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/tan.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/tanh.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/tile.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/to_bool.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/to_float.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/to_int.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/topk.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/transpose.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/unique.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/unsorted_segment_sum.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/unstack.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/where.ts","../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/zeros_like.ts","../node_modules/@tensorflow/tfjs-layers/src/errors.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/executor_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/generic_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/backend/state.ts","../node_modules/@tensorflow/tfjs-layers/src/keras_format/common.ts","../node_modules/@tensorflow/tfjs-layers/src/common.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/math_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/backend/common.ts","../node_modules/@tensorflow/tfjs-layers/src/backend/tfjs_backend.ts","../node_modules/@tensorflow/tfjs-layers/src/keras_format/initializer_config.ts","../node_modules/@tensorflow/tfjs-layers/src/initializers.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/types_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/variable_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/variables.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/topology.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/input_layer.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/executor.ts","../node_modules/@tensorflow/tfjs-layers/src/constraints.ts","../node_modules/@tensorflow/tfjs-layers/src/flags_layers.ts","../node_modules/@tensorflow/tfjs-layers/src/exports_constraints.ts","../node_modules/@tensorflow/tfjs-layers/src/exports_initializers.ts","../node_modules/@tensorflow/tfjs-layers/src/logs.ts","../node_modules/@tensorflow/tfjs-layers/src/base_callbacks.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/serialization.ts","../node_modules/@tensorflow/tfjs-layers/src/losses.ts","../node_modules/@tensorflow/tfjs-layers/src/metrics.ts","../node_modules/@tensorflow/tfjs-layers/src/user_defined_metadata.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/layer_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/serialization_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/version.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/container.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/training_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/training_dataset.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/training_tensors.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/training.ts","../node_modules/@tensorflow/tfjs-layers/src/optimizers.ts","../node_modules/@tensorflow/tfjs-layers/src/models.ts","../node_modules/@tensorflow/tfjs-layers/src/exports.ts","../node_modules/@tensorflow/tfjs-layers/src/activations.ts","../node_modules/@tensorflow/tfjs-layers/src/regularizers.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/advanced_activations.ts","../node_modules/@tensorflow/tfjs-layers/src/utils/conv_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/convolutional.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/convolutional_depthwise.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/recurrent.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/convolutional_recurrent.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/core.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/embeddings.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/merge.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/noise.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/normalization.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/padding.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/pooling.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/wrappers.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/preprocessing/image_preprocessing.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/preprocessing/center_crop.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/preprocessing/category_encoding.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/preprocessing/preprocessing_utils.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/preprocessing/image_resizing.ts","../node_modules/@tensorflow/tfjs-layers/src/backend/random_seed.ts","../node_modules/@tensorflow/tfjs-layers/src/engine/base_random_layer.ts","../node_modules/@tensorflow/tfjs-layers/src/layers/preprocessing/random_width.ts","../node_modules/@tensorflow/tfjs-layers/src/exports_layers.ts","../node_modules/@tensorflow/tfjs-layers/src/exports_metrics.ts","../node_modules/@tensorflow/tfjs-layers/src/exports_regularizers.ts","../node_modules/@tensorflow/tfjs-layers/src/callbacks.ts","../node_modules/@tensorflow/tfjs-converter/src/data/compiled_api.ts","../node_modules/@tensorflow/tfjs-converter/src/flags.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/custom_op/register.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/utils.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/arithmetic.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/basic_math.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/control.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/convolution.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/creation.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/dynamic.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/evaluation.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/graph.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/hash_table.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/image.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/logical.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/matrices.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/normalization.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/reduction.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/slice_join.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/sparse.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/spectral.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/string.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/transformation.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/operation_mapper.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/custom_op/node_value_impl.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/tensor_utils.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/tensor_array.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/tensor_list.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/control_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/convolution_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/dynamic_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/hash_table.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/operation_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/arithmetic_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/basic_math_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/creation_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/evaluation_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/image_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/graph_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/logical_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/matrices_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/normalization_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/ragged_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/reduction_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/slice_join_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/sparse_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/spectral_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/string_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/transformation_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/operations/executors/hash_table_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/execution_context.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/model_analysis.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/graph_executor.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/resource_manager.ts","../node_modules/@tensorflow/tfjs-converter/src/executor/graph_model.ts","../node_modules/@tensorflow/tfjs-converter/src/version.ts","../node_modules/@tensorflow/tfjs-data/src/util/deep_map.ts","../node_modules/@tensorflow/tfjs-data/src/util/deep_clone.ts","../node_modules/@tensorflow/tfjs-data/src/util/ring_buffer.ts","../node_modules/@tensorflow/tfjs-data/src/util/growing_ring_buffer.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/lazy_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/dataset.ts","../node_modules/@tensorflow/tfjs-data/src/datasets/text_line_dataset.ts","../node_modules/@tensorflow/tfjs-data/src/datasets/csv_dataset.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/microphone_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/webcam_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/datasource.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/string_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/byte_chunk_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/file_chunk_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/iterators/url_chunk_iterator.ts","../node_modules/@tensorflow/tfjs-data/src/util/source_util.ts","../node_modules/@tensorflow/tfjs-data/src/sources/file_data_source.ts","../node_modules/@tensorflow/tfjs-data/src/sources/url_data_source.ts","../node_modules/@tensorflow/tfjs-data/src/readers.ts","../node_modules/@tensorflow/tfjs-data/src/version.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/cpu_util.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/backend_cpu.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Abs.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/binary_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Complex.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/zeros_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Identity.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Real.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cast.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/binary_utils.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Add.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Bincount_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BitwiseAnd.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/unary_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/unary_utils.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Ceil.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Concat_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Equal.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Exp.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Expm1.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Floor.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FloorDiv.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherNd_Impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherV2_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Greater.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GreaterEqual.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Less.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LessEqual.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LinSpace_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Log.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Max_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Maximum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Minimum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Multiply.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Neg.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NotEqual.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transpose_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transpose.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Prod.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RaggedGather_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RaggedRange_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RaggedTensorToTensor_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Range_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Rsqrt.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Scatter_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sigmoid.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Slice.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseFillEmptyRows_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseReshape_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseSegmentReduction_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sqrt.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SquaredDifference.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StaticRegexReplace.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StridedSlice_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringNGrams_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringSplit_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringToHashBucketFast_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sub.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tile_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/TopK_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unique_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/version.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/base.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Elu.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LeakyRelu.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Prelu.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Relu.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Relu6.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/fused_utils.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reshape.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchMatMul.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/_FusedMatMul.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Acos.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Acosh.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AddN.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/All.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Any.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ArgMax.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ArgMin.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Asin.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Asinh.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atan.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atan2.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atanh.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/pool_utils.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool3D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool3DGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPoolGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchNorm.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchToSpaceND.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Bincount.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BroadcastArgs.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ClipByValue.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ComplexAbs.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Imag.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Concat.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv2D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv2DBackpropFilter.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv2DBackpropInput.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv3D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv3DBackpropFilterV2.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv3DBackpropInputV2.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cos.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cosh.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/CropAndResize.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cumprod.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cumsum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DenseBincount.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthToSpace.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNative.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNativeBackpropFilter.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNativeBackpropInput.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Diag.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2DBackpropFilter.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2DBackpropInput.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Draw.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Einsum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/EluGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Erf.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ExpandDims.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RealDiv.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/fft_utils.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FFT.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Fill.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FlipLeftRight.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FusedConv2D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FusedDepthwiseConv2D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherNd.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherV2.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IFFT.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsFinite.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsInf.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsNaN.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LinSpace.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Log1p.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalAnd.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalNot.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalOr.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LRN.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LRNGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Max.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool3D.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool3DGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Mean.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Min.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MirrorPad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Mod.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Softmax.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Multinomial.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV3.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV4.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV5.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/OneHot.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ZerosLike.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/OnesLike.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Pack.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/PadV2.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Pow.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RaggedGather.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RaggedRange.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RaggedTensorToTensor.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Range.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reciprocal.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeBilinear.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeBilinearGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeNearestNeighbor.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeNearestNeighborGrad.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reverse.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RotateWithOffset.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Round.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ScatterNd.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SearchSorted_impl.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SearchSorted.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Select.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Selu.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sign.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sin.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sinh.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Softplus.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SpaceToBatchND.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseFillEmptyRows.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseReshape.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseSegmentMean.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseSegmentSum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseToDense.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SplitV.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Square.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Step.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StridedSlice.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringNGrams.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringSplit.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringToHashBucketFast.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tan.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tanh.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/TensorScatterUpdate.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tile.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/TopK.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transform.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unique.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unpack.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/UnsortedSegmentSum.ts","../node_modules/@tensorflow/tfjs-backend-cpu/src/register_all_kernels.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/canvas_util.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/tex_util.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/webgl_util.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/flags_webgl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/glsl_version.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/shader_compiler_util.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/shader_compiler.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_math.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/decode_matrix_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/decode_matrix_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_float_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_float_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_matrix_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_matrix_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_util.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_context.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/shared.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/packing_util.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/pack_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/reshape_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/texture_manager.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/unaryop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/unaryop_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/unpack_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/backend_webgl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/version.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/webgl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/base.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Identity.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Complex.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LeakyRelu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Prelu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/kernel_funcs_utils.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/mulmat_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_complex_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Multiply.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reshape.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/reshape.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/mean_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/reduce_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/reduce.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/transpose_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/transpose_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transpose_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sum_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transpose.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchMatMul_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/_FusedMatMul.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Abs.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Acos.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Acosh.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Add.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/addn_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/addn_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AddN.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/All.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Any.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/argminmax_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/argminmax_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/arg_min_max.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ArgMax.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ArgMin.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Asin.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Asinh.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atan.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atan2.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atanh.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/pool_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool3D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/avg_pool_backprop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool3DGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPoolGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchMatMul.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/batchnorm_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/batchnorm_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchNorm.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/slice_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/slice_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Slice.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchToSpaceND.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Bincount.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BitwiseAnd.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BroadcastArgs.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NotEqual.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Real.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/int.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cast.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Ceil.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/clip_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/clip_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ClipByValue.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/complex_abs_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ComplexAbs.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/concat_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/concat_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Imag.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Concat_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Concat.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/im2col_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2D_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2DBackpropFilter.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2DBackpropInput.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv3D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv3DBackpropFilterV2.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv3DBackpropInputV2.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cos.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cosh.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/crop_and_resize_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/CropAndResize.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/cum_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cum_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cumprod.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cumsum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DenseBincount.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/depth_to_space_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthToSpace.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_gpu_depthwise.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_packed_gpu_depthwise.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNative.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_gpu_depthwise.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNativeBackpropFilter.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNativeBackpropInput.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/diag_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Diag.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/dilation_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Dilation2D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Einsum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Elu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/EluGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Equal.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Erf.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Exp.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ExpandDims.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Expm1.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/fft_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FFT_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FFT.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/fill_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Fill.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/flip_left_right_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FlipLeftRight.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Floor.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FloorDiv.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FusedConv2D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FusedDepthwiseConv2D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/gather_nd_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/GatherNd.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/gather_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/GatherV2.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Greater.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/GreaterEqual.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IFFT.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IsFinite.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IsInf.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IsNaN.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Less.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LessEqual.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LinSpace.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Log.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Log1p.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LogicalAnd.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LogicalNot.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LogicalOr.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LRN.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_grad_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LRNGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Max.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Max_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Maximum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool3D.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/max_pool_backprop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool3DGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Mean.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Mean_impl.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Min.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Minimum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/mirror_pad_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/mirror_pad_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MirrorPad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Mod.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/multinomial_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RealDiv.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sub.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Softmax.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Multinomial.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Neg.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV3.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV4.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV5.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/onehot_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/OneHot.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ZerosLike.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/OnesLike.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Pack.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/pad_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/pad_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/PadV2.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Pow.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Prod.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RaggedGather.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RaggedRange.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RaggedTensorToTensor.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Range.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reciprocal.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Relu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Relu6.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeBilinear.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_backprop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeBilinearGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeNearestNeighbor.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_backprop_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeNearestNeighborGrad.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/reverse_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/reverse_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reverse.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/rotate_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RotateWithOffset.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Round.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Rsqrt.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/scatter_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/scatter_packed_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ScatterNd.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/search_sorted_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SearchSorted.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/select_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Select.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Selu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sigmoid.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sign.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sin.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sinh.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Softplus.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SpaceToBatchND.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseFillEmptyRows.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseReshape.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseSegmentMean.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseSegmentSum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseToDense.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SplitV.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sqrt.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Square.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SquaredDifference.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StaticRegexReplace.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Step.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/strided_slice_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StridedSlice.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StringNGrams.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StringSplit.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StringToHashBucketFast.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tan.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tanh.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/TensorScatterUpdate.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/tile_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tile.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/top_k_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/TopK.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/transform_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transform.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Unique.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Unpack.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/segment_gpu.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/UnsortedSegmentSum.ts","../node_modules/@tensorflow/tfjs-backend-webgl/src/register_all_kernels.ts","../node_modules/@tensorflow/tfjs/src/version.ts","../node_modules/@tensorflow/tfjs/src/index.ts","../node_modules/lower-case/src/index.ts","../node_modules/no-case/src/index.ts","../node_modules/pascal-case/src/index.ts","../node_modules/camel-case/src/index.ts","../node_modules/upper-case-first/src/index.ts","../node_modules/capital-case/src/index.ts","../node_modules/upper-case/src/index.ts","../node_modules/constant-case/src/index.ts","../node_modules/dot-case/src/index.ts","../node_modules/header-case/src/index.ts","../node_modules/param-case/src/index.ts","../node_modules/path-case/src/index.ts","../node_modules/sentence-case/src/index.ts","../node_modules/snake-case/src/index.ts","../node_modules/dijkstrajs/dijkstra.js","../node_modules/encode-utf8/index.js","../node_modules/invariant/browser.js","../node_modules/lodash/_DataView.js","../node_modules/lodash/_Hash.js","../node_modules/lodash/_ListCache.js","../node_modules/lodash/_Map.js","../node_modules/lodash/_MapCache.js","../node_modules/lodash/_Promise.js","../node_modules/lodash/_Set.js","../node_modules/lodash/_SetCache.js","../node_modules/lodash/_Stack.js","../node_modules/lodash/_Symbol.js","../node_modules/lodash/_Uint8Array.js","../node_modules/lodash/_WeakMap.js","../node_modules/lodash/_apply.js","../node_modules/lodash/_arrayFilter.js","../node_modules/lodash/_arrayLikeKeys.js","../node_modules/lodash/_arrayMap.js","../node_modules/lodash/_arrayPush.js","../node_modules/lodash/_arrayReduce.js","../node_modules/lodash/_arraySome.js","../node_modules/lodash/_asciiWords.js","../node_modules/lodash/_assignMergeValue.js","../node_modules/lodash/_assignValue.js","../node_modules/lodash/_assocIndexOf.js","../node_modules/lodash/_baseAssignValue.js","../node_modules/lodash/_baseCreate.js","../node_modules/lodash/_baseFor.js","../node_modules/lodash/_baseGet.js","../node_modules/lodash/_baseGetAllKeys.js","../node_modules/lodash/_baseGetTag.js","../node_modules/lodash/_baseHasIn.js","../node_modules/lodash/_baseIsArguments.js","../node_modules/lodash/_baseIsEqual.js","../node_modules/lodash/_baseIsEqualDeep.js","../node_modules/lodash/_baseIsMatch.js","../node_modules/lodash/_baseIsNative.js","../node_modules/lodash/_baseIsTypedArray.js","../node_modules/lodash/_baseIteratee.js","../node_modules/lodash/_baseKeys.js","../node_modules/lodash/_baseKeysIn.js","../node_modules/lodash/_baseMatches.js","../node_modules/lodash/_baseMatchesProperty.js","../node_modules/lodash/_baseMerge.js","../node_modules/lodash/_baseMergeDeep.js","../node_modules/lodash/_basePickBy.js","../node_modules/lodash/_baseProperty.js","../node_modules/lodash/_basePropertyDeep.js","../node_modules/lodash/_basePropertyOf.js","../node_modules/lodash/_baseRest.js","../node_modules/lodash/_baseSet.js","../node_modules/lodash/_baseSetToString.js","../node_modules/lodash/_baseTimes.js","../node_modules/lodash/_baseToString.js","../node_modules/lodash/_baseUnary.js","../node_modules/lodash/_cacheHas.js","../node_modules/lodash/_castPath.js","../node_modules/lodash/_cloneArrayBuffer.js","../node_modules/lodash/_cloneBuffer.js","../node_modules/lodash/_cloneTypedArray.js","../node_modules/lodash/_copyArray.js","../node_modules/lodash/_copyObject.js","../node_modules/lodash/_coreJsData.js","../node_modules/lodash/_createAssigner.js","../node_modules/lodash/_createBaseFor.js","../node_modules/lodash/_createCompounder.js","../node_modules/lodash/_deburrLetter.js","../node_modules/lodash/_defineProperty.js","../node_modules/lodash/_equalArrays.js","../node_modules/lodash/_equalByTag.js","../node_modules/lodash/_equalObjects.js","../node_modules/lodash/_freeGlobal.js","../node_modules/lodash/_getAllKeys.js","../node_modules/lodash/_getAllKeysIn.js","../node_modules/lodash/_getMapData.js","../node_modules/lodash/_getMatchData.js","../node_modules/lodash/_getNative.js","../node_modules/lodash/_getPrototype.js","../node_modules/lodash/_getRawTag.js","../node_modules/lodash/_getSymbols.js","../node_modules/lodash/_getSymbolsIn.js","../node_modules/lodash/_getTag.js","../node_modules/lodash/_getValue.js","../node_modules/lodash/_hasPath.js","../node_modules/lodash/_hasUnicodeWord.js","../node_modules/lodash/_hashClear.js","../node_modules/lodash/_hashDelete.js","../node_modules/lodash/_hashGet.js","../node_modules/lodash/_hashHas.js","../node_modules/lodash/_hashSet.js","../node_modules/lodash/_initCloneObject.js","../node_modules/lodash/_isIndex.js","../node_modules/lodash/_isIterateeCall.js","../node_modules/lodash/_isKey.js","../node_modules/lodash/_isKeyable.js","../node_modules/lodash/_isMasked.js","../node_modules/lodash/_isPrototype.js","../node_modules/lodash/_isStrictComparable.js","../node_modules/lodash/_listCacheClear.js","../node_modules/lodash/_listCacheDelete.js","../node_modules/lodash/_listCacheGet.js","../node_modules/lodash/_listCacheHas.js","../node_modules/lodash/_listCacheSet.js","../node_modules/lodash/_mapCacheClear.js","../node_modules/lodash/_mapCacheDelete.js","../node_modules/lodash/_mapCacheGet.js","../node_modules/lodash/_mapCacheHas.js","../node_modules/lodash/_mapCacheSet.js","../node_modules/lodash/_mapToArray.js","../node_modules/lodash/_matchesStrictComparable.js","../node_modules/lodash/_memoizeCapped.js","../node_modules/lodash/_nativeCreate.js","../node_modules/lodash/_nativeKeys.js","../node_modules/lodash/_nativeKeysIn.js","../node_modules/lodash/_nodeUtil.js","../node_modules/lodash/_objectToString.js","../node_modules/lodash/_overArg.js","../node_modules/lodash/_overRest.js","../node_modules/lodash/_root.js","../node_modules/lodash/_safeGet.js","../node_modules/lodash/_setCacheAdd.js","../node_modules/lodash/_setCacheHas.js","../node_modules/lodash/_setToArray.js","../node_modules/lodash/_setToString.js","../node_modules/lodash/_shortOut.js","../node_modules/lodash/_stackClear.js","../node_modules/lodash/_stackDelete.js","../node_modules/lodash/_stackGet.js","../node_modules/lodash/_stackHas.js","../node_modules/lodash/_stackSet.js","../node_modules/lodash/_stringToPath.js","../node_modules/lodash/_toKey.js","../node_modules/lodash/_toSource.js","../node_modules/lodash/_unicodeWords.js","../node_modules/lodash/constant.js","../node_modules/lodash/deburr.js","../node_modules/lodash/eq.js","../node_modules/lodash/get.js","../node_modules/lodash/hasIn.js","../node_modules/lodash/identity.js","../node_modules/lodash/isArguments.js","../node_modules/lodash/isArray.js","../node_modules/lodash/isArrayLike.js","../node_modules/lodash/isArrayLikeObject.js","../node_modules/lodash/isBuffer.js","../node_modules/lodash/isFunction.js","../node_modules/lodash/isLength.js","../node_modules/lodash/isObject.js","../node_modules/lodash/isObjectLike.js","../node_modules/lodash/isPlainObject.js","../node_modules/lodash/isSymbol.js","../node_modules/lodash/isTypedArray.js","../node_modules/lodash/kebabCase.js","../node_modules/lodash/keys.js","../node_modules/lodash/keysIn.js","../node_modules/lodash/memoize.js","../node_modules/lodash/merge.js","../node_modules/lodash/pickBy.js","../node_modules/lodash/property.js","../node_modules/lodash/stubArray.js","../node_modules/lodash/stubFalse.js","../node_modules/lodash/toPlainObject.js","../node_modules/lodash/toString.js","../node_modules/lodash/words.js","../node_modules/long/src/long.js","../node_modules/prop-types-extra/lib/all.js","../node_modules/prop-types-extra/lib/utils/createChainableTypeChecker.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/index.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/qrcode/lib/browser.js","../node_modules/qrcode/lib/can-promise.js","../node_modules/qrcode/lib/core/alignment-pattern.js","../node_modules/qrcode/lib/core/alphanumeric-data.js","../node_modules/qrcode/lib/core/bit-buffer.js","../node_modules/qrcode/lib/core/bit-matrix.js","../node_modules/qrcode/lib/core/byte-data.js","../node_modules/qrcode/lib/core/error-correction-code.js","../node_modules/qrcode/lib/core/error-correction-level.js","../node_modules/qrcode/lib/core/finder-pattern.js","../node_modules/qrcode/lib/core/format-info.js","../node_modules/qrcode/lib/core/galois-field.js","../node_modules/qrcode/lib/core/kanji-data.js","../node_modules/qrcode/lib/core/mask-pattern.js","../node_modules/qrcode/lib/core/mode.js","../node_modules/qrcode/lib/core/numeric-data.js","../node_modules/qrcode/lib/core/polynomial.js","../node_modules/qrcode/lib/core/qrcode.js","../node_modules/qrcode/lib/core/reed-solomon-encoder.js","../node_modules/qrcode/lib/core/regex.js","../node_modules/qrcode/lib/core/segments.js","../node_modules/qrcode/lib/core/utils.js","../node_modules/qrcode/lib/core/version-check.js","../node_modules/qrcode/lib/core/version.js","../node_modules/qrcode/lib/renderer/canvas.js","../node_modules/qrcode/lib/renderer/svg-tag.js","../node_modules/qrcode/lib/renderer/utils.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/seedrandom/index.js","../node_modules/seedrandom/lib/alea.js","../node_modules/seedrandom/lib/tychei.js","../node_modules/seedrandom/lib/xor128.js","../node_modules/seedrandom/lib/xor4096.js","../node_modules/seedrandom/lib/xorshift7.js","../node_modules/seedrandom/lib/xorwow.js","../node_modules/seedrandom/seedrandom.js","../node_modules/style-dictionary/lib/utils/deepExtend.js","../node_modules/style-dictionary/lib/utils/es6_.js","../node_modules/style-dictionary/lib/utils/flattenProperties.js","../node_modules/style-dictionary/lib/utils/references/createReferenceRegex.js","../node_modules/style-dictionary/lib/utils/references/defaults.js","../node_modules/style-dictionary/lib/utils/references/usesReference.js","../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js","../node_modules/use-sync-external-store/shim/index.js","../node_modules/use-sync-external-store/shim/with-selector.js","../node_modules/warning/warning.js","../node_modules/classnames/index.js","../node_modules/tslib/tslib.es6.mjs","../webpack/bootstrap","../webpack/runtime/amd define","../webpack/runtime/amd options","../webpack/runtime/compat get default export","../webpack/runtime/create fake namespace object","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/node module decorator","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","../node_modules/react-router/index.ts","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx","../node_modules/react-bootstrap/esm/ThemeProvider.js","../node_modules/react-bootstrap/esm/Container.js","../node_modules/@babel/runtime/helpers/esm/extends.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../node_modules/uncontrollable/lib/esm/utils.js","../node_modules/uncontrollable/lib/esm/hook.js","../node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js","../node_modules/dom-helpers/esm/querySelectorAll.js","../node_modules/@restart/hooks/esm/useMergedRefs.js","../node_modules/@restart/ui/esm/NavContext.js","../node_modules/@restart/ui/esm/SelectableContext.js","../node_modules/@restart/ui/esm/TabContext.js","../node_modules/@restart/ui/esm/DataKey.js","../node_modules/@restart/hooks/esm/useCommittedRef.js","../node_modules/@restart/hooks/esm/useEventCallback.js","../node_modules/@restart/ui/esm/Button.js","../node_modules/@restart/ui/esm/NavItem.js","../node_modules/@restart/ui/esm/Nav.js","../node_modules/@restart/hooks/esm/useForceUpdate.js","../node_modules/react-bootstrap/esm/NavbarContext.js","../node_modules/react-bootstrap/esm/CardHeaderContext.js","../node_modules/react-bootstrap/esm/NavItem.js","../node_modules/@restart/hooks/esm/useIsomorphicEffect.js","../node_modules/@restart/hooks/esm/useResizeObserver.js","../node_modules/@restart/ui/esm/Anchor.js","../node_modules/react-bootstrap/esm/NavLink.js","../node_modules/react-bootstrap/esm/Nav.js","../node_modules/react-bootstrap/esm/NavbarBrand.js","../node_modules/dom-helpers/esm/ownerDocument.js","../node_modules/dom-helpers/esm/getComputedStyle.js","../node_modules/dom-helpers/esm/ownerWindow.js","../node_modules/dom-helpers/esm/hyphenate.js","../node_modules/dom-helpers/esm/hyphenateStyle.js","../node_modules/dom-helpers/esm/isTransform.js","../node_modules/dom-helpers/esm/css.js","../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../node_modules/react-transition-group/esm/config.js","../node_modules/react-transition-group/esm/TransitionGroupContext.js","../node_modules/react-transition-group/esm/utils/reflow.js","../node_modules/react-transition-group/esm/Transition.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../node_modules/dom-helpers/esm/canUseDOM.js","../node_modules/dom-helpers/esm/addEventListener.js","../node_modules/dom-helpers/esm/removeEventListener.js","../node_modules/dom-helpers/esm/listen.js","../node_modules/dom-helpers/esm/transitionEnd.js","../node_modules/dom-helpers/esm/triggerEvent.js","../node_modules/react-bootstrap/esm/transitionEndListener.js","../node_modules/react-bootstrap/esm/createChainedFunction.js","../node_modules/react-bootstrap/esm/triggerBrowserReflow.js","../node_modules/react-bootstrap/esm/TransitionWrapper.js","../node_modules/react-bootstrap/esm/safeFindDOMNode.js","../node_modules/react-bootstrap/esm/Collapse.js","../node_modules/react-bootstrap/esm/NavbarCollapse.js","../node_modules/react-bootstrap/esm/NavbarToggle.js","../node_modules/@restart/hooks/esm/useMediaQuery.js","../node_modules/@restart/hooks/esm/useBreakpoint.js","../node_modules/dom-helpers/esm/activeElement.js","../node_modules/dom-helpers/esm/contains.js","../node_modules/@restart/hooks/esm/useWillUnmount.js","../node_modules/@restart/hooks/esm/useUpdatedRef.js","../node_modules/@restart/ui/esm/ModalManager.js","../node_modules/@restart/ui/esm/getScrollbarWidth.js","../node_modules/@restart/ui/esm/useWindow.js","../node_modules/@restart/ui/esm/useWaitForDOMRef.js","../node_modules/@restart/ui/esm/NoopTransition.js","../node_modules/@restart/ui/esm/useRTGTransitionProps.js","../node_modules/@restart/ui/esm/RTGTransition.js","../node_modules/@restart/ui/esm/ImperativeTransition.js","../node_modules/@restart/ui/esm/Modal.js","../node_modules/@restart/hooks/esm/useMounted.js","../node_modules/@restart/hooks/esm/usePrevious.js","../node_modules/@restart/ui/esm/utils.js","../node_modules/react-bootstrap/esm/Fade.js","../node_modules/react-bootstrap/esm/OffcanvasBody.js","../node_modules/react-bootstrap/esm/OffcanvasToggling.js","../node_modules/react-bootstrap/esm/ModalContext.js","../node_modules/react-bootstrap/esm/CloseButton.js","../node_modules/react-bootstrap/esm/AbstractModalHeader.js","../node_modules/react-bootstrap/esm/OffcanvasHeader.js","../node_modules/react-bootstrap/esm/divWithClassName.js","../node_modules/react-bootstrap/esm/OffcanvasTitle.js","../node_modules/dom-helpers/esm/removeClass.js","../node_modules/react-bootstrap/esm/BootstrapModalManager.js","../node_modules/dom-helpers/esm/addClass.js","../node_modules/dom-helpers/esm/hasClass.js","../node_modules/react-bootstrap/esm/Offcanvas.js","../node_modules/react-bootstrap/esm/NavbarOffcanvas.js","../node_modules/react-bootstrap/esm/NavbarText.js","../node_modules/react-bootstrap/esm/Navbar.js","Components/Common/SiteHomeNav.js","Components/Common/SiteFooter.js","App.js","reportWebVitals.js","../node_modules/react-bootstrap/esm/Row.js","../node_modules/react-bootstrap/esm/Col.js","../node_modules/react-bootstrap/esm/Image.js","../node_modules/react-bootstrap/esm/Button.js","Components/Common/SiteNav.js","../node_modules/@aws-amplify/core/src/Logger/types.ts","../node_modules/@aws-amplify/core/src/Logger/ConsoleLogger.ts","../node_modules/@aws-amplify/core/src/constants.ts","../node_modules/@aws-amplify/core/src/errors/AmplifyError.ts","../node_modules/@aws-amplify/core/src/Hub/index.ts","../node_modules/@aws-amplify/core/src/parseAWSExports.ts","../node_modules/@aws-amplify/core/src/utils/deepFreeze.ts","../node_modules/@aws-amplify/core/src/singleton/Auth/index.ts","../node_modules/@aws-amplify/core/src/singleton/constants.ts","../node_modules/@aws-amplify/core/src/singleton/Amplify.ts","../node_modules/js-cookie/dist/js.cookie.mjs","../node_modules/@aws-amplify/core/src/types/errors.ts","../node_modules/@aws-amplify/core/src/storage/CookieStorage.ts","../node_modules/@aws-amplify/core/src/errors/PlatformNotSupportedError.ts","../node_modules/@aws-amplify/core/src/storage/KeyValueStorage.ts","../node_modules/@aws-amplify/core/src/storage/InMemoryStorage.ts","../node_modules/@aws-amplify/core/src/storage/index.ts","../node_modules/@aws-amplify/core/src/storage/DefaultStorage.ts","../node_modules/@aws-amplify/core/src/storage/utils.ts","../node_modules/@aws-amplify/core/src/utils/globalHelpers/index.ts","../node_modules/@aws-amplify/core/src/storage/SessionStorage.ts","../node_modules/@aws-amplify/core/src/utils/convert/base64/base64Decoder.ts","../node_modules/@aws-amplify/core/src/errors/createAssertionFunction.ts","../node_modules/@aws-amplify/core/src/singleton/Auth/utils/errorHelpers.ts","../node_modules/@aws-amplify/core/src/singleton/Auth/utils/index.ts","../node_modules/@aws-amplify/core/src/utils/deDupeAsyncFunction.ts","../node_modules/@aws-amplify/core/src/clients/internal/composeServiceApi.ts","../node_modules/@aws-amplify/core/src/clients/serde/responseInfo.ts","../node_modules/@aws-amplify/core/src/clients/serde/json.ts","../node_modules/@aws-amplify/auth/src/errors/AuthError.ts","../node_modules/@aws-amplify/auth/src/errors/utils/assertServiceError.ts","../node_modules/@aws-amplify/core/src/clients/endpoints/partitions.ts","../node_modules/@aws-amplify/core/src/clients/endpoints/getDnsSuffix.ts","../node_modules/@aws-amplify/core/src/clients/middleware/retry/middleware.ts","../node_modules/@aws-amplify/core/src/clients/internal/composeTransferHandler.ts","../node_modules/@aws-amplify/core/src/clients/utils/memoization.ts","../node_modules/@aws-amplify/core/src/clients/handlers/fetch.ts","../node_modules/@aws-amplify/core/src/clients/handlers/unauthenticated.ts","../node_modules/@aws-amplify/core/src/clients/middleware/userAgent/middleware.ts","../node_modules/@aws-amplify/core/src/clients/middleware/retry/isClockSkewError.ts","../node_modules/@aws-amplify/core/src/clients/middleware/retry/defaultRetryDecider.ts","../node_modules/@aws-amplify/core/src/clients/middleware/retry/jitteredBackoff.ts","../node_modules/@aws-amplify/core/src/utils/retry/jitteredBackoff.ts","../node_modules/@aws-amplify/core/src/utils/retry/constants.ts","../node_modules/@aws-amplify/core/src/utils/amplifyUrl/index.ts","../node_modules/@aws-amplify/core/src/Platform/types.ts","../node_modules/@aws-amplify/core/src/Platform/version.ts","../node_modules/@aws-amplify/core/src/Platform/detection/helpers.ts","../node_modules/@aws-amplify/core/src/Platform/detection/index.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Expo.ts","../node_modules/@aws-amplify/core/src/Platform/detection/ReactNative.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Next.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Nuxt.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Angular.ts","../node_modules/@aws-amplify/core/src/Platform/detection/React.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Vue.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Svelte.ts","../node_modules/@aws-amplify/core/src/Platform/detection/Web.ts","../node_modules/@aws-amplify/core/src/Platform/detectFramework.ts","../node_modules/@aws-amplify/core/src/Platform/customUserAgent.ts","../node_modules/@aws-amplify/core/src/Platform/index.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/utils.ts","../node_modules/@aws-amplify/auth/src/errors/constants.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/types.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/userContextData.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/refreshAuthTokens.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/types.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/errorHelpers.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/TokenStore.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/tokenProvider.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/types.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts","../node_modules/@aws-crypto/sha256-js/src/constants.ts","../node_modules/@aws-crypto/sha256-js/src/RawSha256.ts","../node_modules/@aws-crypto/util/src/convertToBuffer.ts","../node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js","../node_modules/@aws-crypto/sha256-js/src/jsSha256.ts","../node_modules/@aws-crypto/util/src/isEmptyData.ts","../node_modules/@smithy/util-hex-encoding/dist-es/index.js","../node_modules/@aws-amplify/core/src/awsClients/cognitoIdentity/base.ts","../node_modules/@aws-amplify/core/src/awsClients/cognitoIdentity/getCredentialsForIdentity.ts","../node_modules/@aws-amplify/core/src/awsClients/cognitoIdentity/getId.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/utils.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/index.ts","../node_modules/aws-amplify/src/initSingleton.ts","../node_modules/@aws-amplify/ui/dist/esm/utils/utils.mjs","../node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js","../node_modules/@xstate/react/es/useActor.js","../node_modules/@xstate/react/es/useSelector.js","../node_modules/@xstate/react/es/utils.js","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/actor.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/facade.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/getRoute.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/context/AuthenticatorContext.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticator/constants.mjs","../node_modules/@aws-amplify/ui/dist/esm/types/authenticator/attributes.mjs","../node_modules/@aws-amplify/ui/dist/esm/i18n/country-dial-codes.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/constants.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/form.mjs","../node_modules/@aws-amplify/core/src/I18n/I18n.ts","../node_modules/@aws-amplify/core/src/I18n/errorHelpers.ts","../node_modules/@aws-amplify/core/src/I18n/index.ts","../node_modules/@aws-amplify/ui/dist/esm/i18n/dictionaries/authenticator/de.mjs","../node_modules/@aws-amplify/ui/dist/esm/i18n/translations.mjs","../node_modules/@aws-amplify/ui/dist/esm/i18n/dictionaries/index.mjs","../node_modules/@aws-amplify/ui/dist/esm/i18n/dictionaries/authenticator/defaultTexts.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/formFields/utils.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/formFields/defaults.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/formFields/formFields.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/constants.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticator/utils.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/utils.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticator/useAuthenticator.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticatorInitMachine/useAuthenticatorInitMachine.mjs","../node_modules/@aws-amplify/ui/dist/esm/utils/setUserAgent/constants.mjs","../node_modules/@aws-amplify/ui/dist/esm/utils/setUserAgent/setUserAgent.mjs","../node_modules/xstate/es/_virtual/_tslib.js","../node_modules/xstate/es/types.js","../node_modules/xstate/es/constants.js","../node_modules/xstate/es/utils.js","../node_modules/xstate/es/actionTypes.js","../node_modules/xstate/es/environment.js","../node_modules/xstate/es/stateUtils.js","../node_modules/xstate/es/actions.js","../node_modules/xstate/es/State.js","../node_modules/xstate/es/scheduler.js","../node_modules/xstate/es/serviceScope.js","../node_modules/xstate/es/Actor.js","../node_modules/xstate/es/registry.js","../node_modules/xstate/es/devTools.js","../node_modules/xstate/es/behaviors.js","../node_modules/xstate/es/interpreter.js","../node_modules/@xstate/react/es/useConstant.js","../node_modules/@xstate/react/es/useInterpret.js","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/getCurrentUser.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/internal/getCurrentUser.ts","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/defaultAuthHubHandler.mjs","../node_modules/xstate/es/invokeUtils.js","../node_modules/xstate/es/StateNode.js","../node_modules/xstate/es/Machine.js","../node_modules/xstate/es/index.js","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/utils.mjs","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actions.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/utils.mjs","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/guards.mjs","../node_modules/@aws-amplify/ui/dist/esm/validators/index.mjs","../node_modules/@aws-amplify/core/src/utils/convert/base64/base64Encoder.ts","../node_modules/@aws-amplify/core/src/utils/convert/base64/bytesToString.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/types/errors.ts","../node_modules/@aws-amplify/auth/src/errors/types/validation.ts","../node_modules/@aws-amplify/auth/src/common/AuthErrorStrings.ts","../node_modules/@aws-amplify/auth/src/errors/utils/assertValidationError.ts","../node_modules/@aws-amplify/auth/src/utils/getAuthUserAgentValue.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signInStore.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/textEncoder/index.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/constants.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getBytesFromHex.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHexFromBytes.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHashFromData.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHashFromHex.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getPaddedHex.ts","../node_modules/@aws-amplify/core/src/utils/WordArray.ts","../node_modules/@aws-amplify/core/src/utils/cryptoSecureRandomInt.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getRandomBytes.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getRandomString.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/calculate/calculateU.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHkdfKey.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/calculate/calculateA.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getAuthenticationHelper.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getNowString.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getSignatureString.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signInHelpers.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/cacheTokens.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/dispatchSignedInHubEvent.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithSRP.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signIn.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithUserPassword.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithCustomAuth.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/apiHelpers.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/autoSignIn.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signUpHelpers.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmSignIn.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/resetPassword.ts","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/defaultServices.mjs","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signUp.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmSignUp.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmResetPassword.ts","../node_modules/@aws-amplify/core/src/singleton/apis/internal/fetchAuthSession.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/fetchUserAttributes.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/resendSignUpCode.ts","../node_modules/@aws-amplify/core/src/utils/isBrowser.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signInWithRedirectStore.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/oAuthStore.ts","../node_modules/@aws-amplify/auth/src/Errors.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/createOAuthError.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/inflightPromise.ts","../node_modules/@aws-amplify/auth/src/types/Auth.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/validateState.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts","../node_modules/@aws-amplify/core/src/utils/urlSafeDecode.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/getRedirectUrl.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/handleFailure.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/enableOAuthListener.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/types/models.ts","../node_modules/@aws-amplify/auth/src/utils/openAuthSession.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts","../node_modules/@aws-amplify/core/src/utils/generateRandomString.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/generateState.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithRedirect.ts","../node_modules/@aws-amplify/core/src/utils/urlSafeEncode.ts","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/utils.mjs","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/signIn.mjs","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/signUp.mjs","../node_modules/@aws-amplify/core/src/singleton/apis/clearCredentials.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signOut.ts","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/signOut.mjs","../node_modules/@aws-amplify/core/src/singleton/apis/fetchAuthSession.ts","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/verifyUserAttributes.mjs","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmUserAttribute.ts","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/index.mjs","../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/forgotPassword.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/context/AuthenticatorProvider.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/version.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/hooks/useDeprecationWarning.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/hooks/useDeprecationWarning.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/hooks/useCustomComponents/useCustomComponents.mjs","../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/textUtil.mjs","../node_modules/@aws-amplify/ui/dist/esm/utils/classNames.mjs","../node_modules/@aws-amplify/ui/dist/esm/types/primitives/componentClassName.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/primitiveWithForwardRef.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Fieldset/useFieldset.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/utils.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/types/style.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/borderWidths.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/colors.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/fontSizes.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/fontWeights.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/opacities.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/radii.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/space.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/time.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/defaultTheme.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/index.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/index.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/accordion.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/alert.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/authenticator.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/autocomplete.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/badge.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/breadcrumbs.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/button.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/card.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/checkbox.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/checkboxField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/collection.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/copy.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/dialCodeSelect.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/divider.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/dropZone.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/field.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldControl.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldGroup.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldMessages.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldset.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/flex.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/heading.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/icon.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/highlightMatch.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/image.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/inAppMessaging.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/input.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/link.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/liveness.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/loader.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/menu.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/message.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/pagination.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/passwordField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/phoneNumberField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/placeholder.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/radio.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/radioGroup.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/rating.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/searchField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/select.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/selectField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/sliderField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/stepperField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/storagemanager.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/switchField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/table.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/tabs.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/text.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/textAreaField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/textField.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/toggleButton.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/toggleButtonGroup.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/fonts.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/lineHeights.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/outlineOffsets.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/outlineWidths.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/shadows.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/transforms.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/breakpoints.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/constants.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/utils.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/types/theme.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/responsive/utils.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/responsive/useBreakpoint.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/responsive/getMediaQueries.mjs","../node_modules/@aws-amplify/ui/dist/esm/theme/createTheme.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/ThemeProvider/ThemeContext.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/hooks/useTheme.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/styleUtils.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/getStyleValue.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/View/View.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Flex/Flex.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Loader/Loader.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Button/Button.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Heading/Heading.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Text/Text.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/helpers/utils.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/hooks/useFormHandlers/useFormHandlers.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/context/IconsContext.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/context/useIcons.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconCheckCircle.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconError.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconInfo.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconWarning.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Alert/AlertIcon.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconClose.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Alert/Alert.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/RemoteErrorMessage.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/VisuallyHidden/VisuallyHidden.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconVisibilityOff.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconVisibility.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PasswordField/ShowPasswordButton.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Field/FieldDescription.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Field/FieldErrorMessage.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/FieldGroup/FieldGroup.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Input/Input.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Label/Label.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/splitPrimitiveProps.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/useLayoutEffect.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/useStableId.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/TextField/TextField.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PasswordField/PasswordField.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconExpandMore.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Select/Select.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/SelectField/SelectField.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PhoneNumberField/DialCodeSelect.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PhoneNumberField/PhoneNumberField.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/shared/ValidationErrors.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/FormField.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/FormFields.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/RouteContainer/RouteContainer.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ConfirmSignUp/ConfirmSignUp.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ForceNewPassword/ForceNewPassword.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/ConfirmSignInFooter.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/SetupTotp/SetupTotp.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsContext.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsItem.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsList.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsPanel.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsContainer.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/Tabs.mjs","../node_modules/@aws-amplify/ui/dist/esm/types/authenticator/user.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Divider/Divider.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/Icon.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/FederatedSignIn/FederatedSignInButtons/FederatedSignInButton.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/FederatedSignIn/FederatedSignIn.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/SignIn/SignIn.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/SignUp/SignUp.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/SignInSignUpTabs.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/TwoButtonSubmitFooter.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/VerifyUser/ConfirmVerifyUser.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/RadioGroupField/context.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Radio/Radio.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Fieldset/Fieldset.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/getTestId.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/primitives/RadioGroupField/RadioGroupField.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/VerifyUser/VerifyUser.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ConfirmSignIn/ConfirmSignIn.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ForgotPassword/ConfirmResetPassword.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ForgotPassword/ForgotPassword.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/utils.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/Router/Router.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/hooks/useCustomComponents/defaultComponents.mjs","../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/Authenticator.mjs","../node_modules/@aws-amplify/ui-react-core/dist/esm/hooks/useSetUserAgent.mjs","aws-exports.js","Components/Pages/HomePage.js","../node_modules/react-bootstrap/esm/CardBody.js","../node_modules/react-bootstrap/esm/CardFooter.js","../node_modules/react-bootstrap/esm/CardHeader.js","../node_modules/react-bootstrap/esm/CardImg.js","../node_modules/react-bootstrap/esm/CardImgOverlay.js","../node_modules/react-bootstrap/esm/CardLink.js","../node_modules/react-bootstrap/esm/CardSubtitle.js","../node_modules/react-bootstrap/esm/CardText.js","../node_modules/react-bootstrap/esm/CardTitle.js","../node_modules/react-bootstrap/esm/Card.js","../node_modules/react-bootstrap/esm/Badge.js","recommendationSystem.js","../node_modules/react-bootstrap/esm/Feedback.js","../node_modules/react-bootstrap/esm/FormContext.js","../node_modules/react-bootstrap/esm/FormCheckInput.js","../node_modules/react-bootstrap/esm/FormCheckLabel.js","../node_modules/react-bootstrap/esm/FormCheck.js","../node_modules/react-bootstrap/esm/ElementChildren.js","../node_modules/react-bootstrap/esm/FormControl.js","../node_modules/react-bootstrap/esm/FormFloating.js","../node_modules/react-bootstrap/esm/FormGroup.js","../node_modules/react-bootstrap/esm/FormLabel.js","../node_modules/react-bootstrap/esm/FormRange.js","../node_modules/react-bootstrap/esm/FormSelect.js","../node_modules/react-bootstrap/esm/FormText.js","../node_modules/react-bootstrap/esm/Switch.js","../node_modules/react-bootstrap/esm/FloatingLabel.js","../node_modules/react-bootstrap/esm/Form.js","Components/Pages/Profile.js","../node_modules/@aws-amplify/auth/src/providers/cognito/apis/deleteUser.ts","Components/Pages/Matchmaking.js","Components/Pages/UpcomingHackathons.js","Components/Pages/ErrorPage.js","Components/Pages/About.js","index.js"],"sourcesContent":["/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, DataToGPUOptions, GPUData} 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;\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 {\n private data = new WeakMap();\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;\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 {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n readToGPU(dataId: object, options?: DataToGPUOptions): GPUData {\n return notYetImplemented('readToGPU');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object, force?: boolean): boolean {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n return notYetImplemented('move');\n }\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, DataTypeMap, FlatVector, NumericDataType, RecursiveArray, TensorLike, TypedArray} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n swap(array, counter, index);\n }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n * as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n // tslint:disable-next-line:no-any\n array: any[]|Uint32Array|Int32Array|Float32Array,\n // tslint:disable-next-line:no-any\n array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n if (array.length !== array2.length) {\n throw new Error(\n `Array sizes must match to be shuffled together ` +\n `First array length was ${array.length}` +\n `Second array length was ${array2.length}`);\n }\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element of each array with it\n swap(array, counter, index);\n swap(array2, counter, index);\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap(\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().\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|TypedArray>(\n arr: T|RecursiveArray, 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 indices to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indices to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number,\n scheduleFn: (functionRef: Function, delay: number) => void =\n setTimeout): Promise {\n return new Promise((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 scheduleFn(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(\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(\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(\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 Uint8ClampedArray {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS\n * is not possible since it depends on the encoding of the html page that\n * serves the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (\n values instanceof Int32Array || values instanceof Uint8Array ||\n values instanceof Uint8ClampedArray) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\nfunction createNestedArray(\n offset: number, shape: number[], a: TypedArray, isComplex = false) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0] * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n shape: number[], a: TypedArray, isComplex = false) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}${\n isComplex ? ' for a complex tensor' : ''}.`);\n }\n\n return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function makeOnesTypedArray(\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(\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(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a\n * tensor/multidimentional array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise {\n // We chose to not use 'obj instanceOf Promise' for two reasons:\n // 1. It only reliably works for es6 Promise, not other Promise\n // implementations.\n // 2. It doesn't work with framework that uses zone.js. zone.js monkey\n // patch the async calls, so it is possible the obj (patched) is\n // comparing to a pre-patched Promise.\n return object && object.then && typeof object.then === 'function';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // Jasmine spies on this in 'environment_test.ts'\n getQueryParams = getQueryParams;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platformName}.`);\n }\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because\n // the environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n }\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (isPromise(flagValue)) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue;\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n 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 {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = this.getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n value = value.toLowerCase();\n if (value === 'true' || value === 'false') {\n return value === 'true';\n } else if (`${+ value}` === value) {\n return +value;\n }\n throw new Error(\n `Could not parse value flag value ${value} for flag ${flagName}.`);\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map} {\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 {\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(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap, TensorInfo} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {DataType, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick;\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;\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;\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;\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;\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;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick;\nexport interface BincountAttrs {\n size: number;\n}\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick;\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;\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;\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;\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;\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;\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;\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;\nexport interface Conv3DBackpropInputV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumprod = 'Cumprod';\nexport type CumprodInputs = Pick;\nexport interface CumprodAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick;\nexport interface DenseBincountAttrs {\n size: number;\n binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick;\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;\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;\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;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick;\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;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick;\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;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick;\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;\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;\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;\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;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick;\nexport interface GatherV2Attrs {\n axis: number;\n batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick;\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;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick;\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;\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;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogicalXor = 'LogicalXor';\nexport type LogicalXorInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LowerBound = 'LowerBound';\nexport type LowerBoundInputs =\n Pick;\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick;\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;\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;\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;\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;\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;\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;\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;\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;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick;\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;\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;\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;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick;\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;\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;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n dtype: DataType;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const RaggedGather = 'RaggedGather';\nexport type RaggedGatherInputs = {\n paramsNestedSplits: TensorInfo[]\n}&Pick;\nexport interface RaggedGatherAttrs {\n outputRaggedRank: number;\n}\n\nexport const RaggedTensorToTensor = 'RaggedTensorToTensor';\nexport type RaggedTensorToTensorInputs =\n Pick&\n {rowPartitionTensors: TensorInfo[]};\nexport interface RaggedTensorToTensorAttrs {\n rowPartitionTypes: string[];\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick;\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;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const SearchSorted = 'SearchSorted';\nexport type SearchSortedInputs =\n Pick;\nexport interface SearchSortedAttrs {\n side: 'left'|'right';\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick;\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;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n Pick;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n Pick;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n Pick;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n Pick;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick;\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;\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick;\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;\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;\nexport interface StringSplitAttrs {\n skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick;\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;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick;\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;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const UpperBound = 'UpperBound';\nexport type UpperBoundInputs =\n Pick;\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;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {DataType, RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map());\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;\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|undefined;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n log.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n log.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string, backendName: string) {\n return `${backendName}_${kernelName}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(...msg);\n }\n}\n\nexport function log(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.log(...msg);\n }\n}\n","/**\n * @license\n * Copyright 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 {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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,\n extraInfo: Promise\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;\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(\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from(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 =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from(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\n// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265\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 {\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 {\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 {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor;\n }\n}\n\nexport interface DataToGPUWebGLOption {\n customTexShape?: [number, number];\n}\n\nexport type DataToGPUOptions = DataToGPUWebGLOption;\n\nexport interface GPUData {\n tensorRef: Tensor;\n texture?: WebGLTexture;\n buffer?: GPUBuffer;\n texShape?: [number, number];\n bufSize?: number;\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast(x: T, dtype: DataType): T;\n buffer(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer;\n print(x: T, verbose: boolean): void;\n clone(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 {\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(): Promise> {\n const vals = await this.data();\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(): TensorBuffer {\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 {\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(): Promise {\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;\n }\n\n /**\n * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`\n * and `data()`, this method prevents data from being downloaded to CPU.\n *\n * For WebGL backend, the data will be stored on a densely packed texture.\n * This means that the texture will use the RGBA channels to store value.\n *\n * For WebGPU backend, the data will be stored on a buffer. There is no\n * parameter, so can not use a user-defined size to create the buffer.\n *\n * @param options:\n * For WebGL,\n * - customTexShape: Optional. If set, will use the user defined\n * texture shape to create the texture.\n *\n * @returns For WebGL backend, a GPUData contains the new texture and\n * its information.\n * {\n * tensorRef: The tensor that is associated with this texture,\n * texture: WebGLTexture,\n * texShape: [number, number] // [height, width]\n * }\n *\n * For WebGPU backend, a GPUData contains the new buffer and\n * its information.\n * {\n * tensorRef: The tensor that is associated with this buffer,\n * buffer: GPUBuffer,\n * bufSize: number\n * }\n *\n * Remember to dispose the GPUData after it is used by\n * `res.tensorRef.dispose()`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataToGPU(options?: DataToGPUOptions): GPUData {\n this.throwIfDisposed();\n return trackerFn().readToGPU(this.dataId, options);\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync(): 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 {\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(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(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable;\n }\n}\n\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport function getGlobalTensorClass() {\n // Use getGlobal so that we can augment the Tensor class across package\n // boundaries 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 extends Tensor {\n dtype: NumericDataType;\n dataSync(): DataTypeMap[D];\n data(): Promise;\n dataToGPU(options?: DataToGPUOptions): GPUData;\n}\n\nexport interface StringTensor extends Tensor {\n dtype: 'string';\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor;\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 extends Tensor {\n name: string;\n\n constructor(\n initialValue: Tensor, 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): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n","/**\n * @license\n * Copyright 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 =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray {\n [index: number]: T|RecursiveArray;\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|\n RecursiveArray|RecursiveArray|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport {getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap, TensorInfo} from './kernel_registry';\nimport * as log from './log';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataId, DataToGPUOptions, GPUData, 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 = (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 =\n (...inputs: Array) => {\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;\n extraInfo: string | Promise;\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;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\ninterface RegisteredKernelInvocation {\n kernelName: string;\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation {\n forwardFunc: ForwardFunc;\n backwardsFunc: (dy: T, saved: Tensor[]) => {\n [P in keyof I]: () => I[P]\n };\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation(\n kernelInvocation: RegisteredKernelInvocation|\n CustomGradKernelInvocation):\n kernelInvocation is RegisteredKernelInvocation {\n return (kernelInvocation as RegisteredKernelInvocation).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();\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,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise {\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 {\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,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n log.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise {\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, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend) &&\n typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n const refCount = srcBackend.refCount(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId, true);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype, refCount);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy(nameOrFn: string|ScopeFn, fn?: ScopeFn):\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(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(\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(\n kernelParams: RegisteredKernelInvocation|\n CustomGradKernelInvocation): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n\n let out: TensorInfo|TensorInfo[];\n\n const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n kernelParams.kernelName :\n this.state.activeScope != null ? this.state.activeScope.name : '';\n\n // Create the kernelFunc from either a registered kernel OR passed in\n // forward/backward functions (used by custom grad). In this context a\n // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n if (isRegisteredKernelInvocation(kernelParams)) {\n const {kernelName, inputs, attrs} = kernelParams;\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const kernel = getKernel(kernelName, this.backendName);\n util.assert(\n kernel != null,\n () => `Cannot find registered kernel '${kernelName}' for backend '${\n this.backendName}'`);\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n\n const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n // todo (yassogba) remove this option (Tensor) when node backend\n // methods have been modularized and they all return tensorInfo.\n // TensorInfos do not have a rank attribute.\n if ((outInfo as Tensor).rank != null) {\n return outInfo as Tensor;\n }\n return this.makeTensorFromTensorInfo(outInfo);\n });\n\n // Save any required inputs and outputs.\n\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since there would be no backprop for these tensors\n // (which would otherwise dispose them).\n if (isTapeOn) {\n const tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const {forwardFunc} = kernelParams;\n // Running a customGrad op.\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n // Scope name is used to print a more helpful error message if needed.\n this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n //\n // Run the kernelFunc. Optionally profiling it.\n //\n const {inputs, attrs} = kernelParams;\n const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n null :\n kernelParams.backwardsFunc;\n\n let kernelProfile: KernelProfile;\n this.scopedRun(\n // Stop recording to a tape when running a kernel.\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelOrScopeName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelOrScopeName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // We return an empty list rather than throw an error because the kernel we\n // are looking up may not actually be relevant to backproping through the\n // overall function\n //\n // See 'does not error if irrelevant (pruned) ops are missing grads' test\n // in gradients_test.ts for an example.\n return [];\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n * @deprecated\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const tensorInfo: TensorInfo = {dataId, shape, dtype};\n return this.makeTensorFromTensorInfo(tensorInfo, backend);\n }\n\n /**\n * Internal method used by backends. Makes a new tensor that is a wrapper\n * around an existing data id in TensorInfo. It doesn't create a new data id,\n * only increments the ref count used in memory tracking.\n */\n makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend):\n Tensor {\n const {dataId, shape, dtype} = tensorInfo;\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n trackTensor(a: Tensor, backend: KernelBackend): void {\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.numBytes += bytes;\n\n if (!this.state.tensorInfo.has(a.dataId)) {\n this.state.numDataBuffers++;\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes\n });\n }\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n // Track the tensor by dataId and increase the refCount for the dataId in the\n // backend.\n // TODO(pyu10055): This is currently used by makeVariable method, to increase\n // refCount on the backend for the dataId. It can potentially be replaced with\n // Identity op indead of calling backend directly.\n incRef(a: Tensor, backend: KernelBackend): void {\n this.trackTensor(a, backend);\n this.backend.incRef(a.dataId);\n }\n\n removeDataId(dataId: DataId, backend: KernelBackend) {\n if (this.state.tensorInfo.has(dataId) &&\n this.state.tensorInfo.get(dataId).backend === backend) {\n this.state.tensorInfo.delete(dataId);\n this.state.numDataBuffers--;\n }\n }\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n this.state.numBytes -= info.bytes;\n }\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n const bytes = a.size * util.bytesPerElement(a.dtype);\n this.state.numBytes -= bytes;\n }\n\n // Remove the reference to dataId if backend dispose the data successfully\n if (info.backend.disposeData(a.dataId)) {\n this.removeDataId(a.dataId, info.backend);\n }\n\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise)):\n Promise {\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(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(\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),\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(f: CustomGradientFunc):\n (...args: Array) => 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 = (_, 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 {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readToGPU(dataId, options);\n }\n\n async time(query: () => void): Promise {\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(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as {} as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernel(Add, inputs as {} as NamedTensorMap);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\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 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n\n/** Whether to check computation result for errors. */\nENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => true);\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);\n\n/** Experimental flag, whether enter compile only phase. */\nENV.registerFlag('ENGINE_COMPILE_ONLY', () => false);\n\n/** Whether to enable canvas2d willReadFrequently for GPU backends */\nENV.registerFlag('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU', () => false);\n\n/** Whether to use setTimeoutCustom */\nENV.registerFlag('USE_SETTIMEOUTCUSTOM', () => false);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {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(\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(\n arg: Array, 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 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nlet isMobileMockValue: boolean|undefined;\n\nexport function mockIsMobile(value: boolean|undefined) {\n isMobileMockValue = value;\n}\n\nexport function isMobile(nav?: Navigator): boolean {\n if (isMobileMockValue !== undefined) {\n return isMobileMockValue;\n }\n if (nav || _isNavigatorDefined()) {\n if (!nav) {\n nav = navigator;\n }\n if (nav.product === 'ReactNative') {\n return true;\n }\n\n const a = nav.userAgent || nav.vendor ||\n // tslint:disable-next-line:no-any\n (typeof window !== 'undefined' ? (window as any).opera : '');\n // Use `navigator.userAgentData.mobile` as fallback.\n if (!a) {\n // tslint:disable-next-line:no-any\n const navAny = nav as any;\n return navAny.userAgentData && navAny.userAgentData.mobile;\n }\n // tslint:disable-next-line:max-line-length\n return /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (isPromise(result)) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_(real: T|TensorLike, imag: T|TensorLike): T {\n const $real = convertToTensor(real, 'real', 'complex');\n const $imag = convertToTensor(imag, 'imag', 'complex');\n util.assertShapesMatch(\n $real.shape, $imag.shape,\n `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n `must match in call to tf.complex().`);\n\n const inputs: ComplexInputs = {real: $real, imag: $imag};\n return ENGINE.runKernel(Complex, inputs as {} as NamedTensorMap);\n}\n\nexport const complex = op({complex_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {TensorLike, TypedArray} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike, shape: number[], inferredShape: number[],\n dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`. If the values are strings,\n * they will be encoded as utf-8 and kept as `Uint8Array[]`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor(\n values: TensorLike, shape?: ShapeMap[R], dtype?: DataType): Tensor {\n const inferredShape = inferShape(values, dtype);\n return makeTensor(values, shape, inferredShape, dtype) as 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\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;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n Promise;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n save?: SaveHandler;\n load?: LoadHandler;\n}\n\n/**\n * Type definition for handlers of synchronous loading operations.\n */\nexport type LoadHandlerSync = () => ModelArtifacts;\n\n/**\n * Type definition for handlers of synchronous saving operations.\n */\nexport type SaveHandlerSync = (modelArtifact: ModelArtifacts) => SaveResult;\n\n/**\n * Interface for a synchronous model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport type IOHandlerSync = {\n save?: SaveHandlerSync;\n load?: LoadHandlerSync;\n};\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n /**\n * List all models in the model store.\n *\n * @returns A dictionary mapping paths of existing models to their\n * model artifacts info. Model artifacts info include type of the model's\n * topology, byte sizes of the topology, weights, etc.\n */\n listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n /**\n * Remove a model specified by `path`.\n *\n * @param path\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n */\n removeModel(path: string): Promise;\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;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n /**\n * Is this request for a binary file (as opposed to a json file)\n */\n isBinary?: boolean;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array> = [];\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(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 and weights.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param weightSpecs The list of WeightsManifestEntry for the model. Must be\n * passed if the modelJSON has a weightsManifest.\n * @param weightData An ArrayBuffer of weight data for the model corresponding\n * to the weights in weightSpecs. Must be passed if the modelJSON has a\n * weightsManifest.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport function getModelArtifactsForJSONSync(\n modelJSON: ModelJSON, weightSpecs?: WeightsManifestEntry[],\n weightData?: ArrayBuffer): ModelArtifacts {\n\n const modelArtifacts: ModelArtifacts = {\n modelTopology: modelJSON.modelTopology,\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy\n };\n\n if (modelJSON.trainingConfig != null) {\n modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n }\n if (modelJSON.weightsManifest != null) {\n if (!weightSpecs) {\n throw new Error('modelJSON has weightsManifest but weightSpecs is null');\n }\n if (!weightData) {\n throw new Error('modelJSON has weightsManifest but weightData is null');\n }\n modelArtifacts.weightSpecs = weightSpecs;\n modelArtifacts.weightData = weightData;\n }\n if (modelJSON.signature != null) {\n modelArtifacts.signature = modelJSON.signature;\n }\n if (modelJSON.userDefinedMetadata != null) {\n modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n }\n if (modelJSON.modelInitializer != null) {\n modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n }\n\n return modelArtifacts;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n * reads weights from the listed path(s), and returns a Promise of the\n * weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n modelJSON: ModelJSON,\n loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n /* weightSpecs */ WeightsManifestEntry[], /* weightData */ ArrayBuffer\n ]>): Promise {\n let weightSpecs: WeightsManifestEntry[] | undefined;\n let weightData: ArrayBuffer | undefined;\n\n if (modelJSON.weightsManifest != null) {\n [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);\n }\n\n return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n modelArtifacts.weightData.byteLength,\n };\n}\n\n/**\n * Concatenate the weights stored in a WeightsManifestConfig into a list of\n * WeightsManifestEntry\n *\n * @param weightsManifest The WeightsManifestConfig to extract weights from.\n * @returns A list of WeightsManifestEntry of the weights in the weightsManifest\n */\nexport function getWeightSpecs(weightsManifest: WeightsManifestConfig):\n WeightsManifestEntry[] {\n const weightSpecs: WeightsManifestEntry[] = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n return weightSpecs;\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\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 {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise((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 {\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;\n }\n\n async load(): Promise {\n return this.databaseAction(this.modelPath) as Promise;\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 {\n return new Promise((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 {\n path = maybeStripScheme(path);\n return new Promise((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;\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 {\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 = {\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 {\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 {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n removeItems(keys);\n return info;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = ModelStoreManagerRegistry.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(ModelStoreManagerRegistry.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a registered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise {\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 {\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 {\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 // For setTimeoutCustom\n private messageName = 'setTimeoutCustom';\n private functionRefs: Function[] = [];\n private handledMessageCount = 0;\n private hasEventListener = false;\n\n fetch(path: string, init?: RequestInit): Promise {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n\n // If the setTimeout nesting level is greater than 5 and timeout is less\n // than 4ms, timeout will be clamped to 4ms, which hurts the perf.\n // Interleaving window.postMessage and setTimeout will trick the browser and\n // avoid the clamp.\n setTimeoutCustom(functionRef: Function, delay: number): void {\n if (!window || !env().getBool('USE_SETTIMEOUTCUSTOM')) {\n setTimeout(functionRef, delay);\n return;\n }\n\n this.functionRefs.push(functionRef);\n setTimeout(() => {\n window.postMessage(\n {name: this.messageName, index: this.functionRefs.length - 1}, '*');\n }, delay);\n\n if (!this.hasEventListener) {\n this.hasEventListener = true;\n window.addEventListener('message', (event: MessageEvent) => {\n if (event.source === window && event.data.name === this.messageName) {\n event.stopPropagation();\n const functionRef = this.functionRefs[event.data.index];\n functionRef();\n this.handledMessageCount++;\n if (this.handledMessageCount === this.functionRefs.length) {\n this.functionRefs = [];\n this.handledMessageCount = 0;\n }\n }\n }, true);\n }\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise;\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 {\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') && !env().get('IS_BROWSER')) {\n env().setPlatform('node', new PlatformNode());\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer(shape, dtype, values);\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const cast = op({cast_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernel(Identity, inputs as {} as NamedTensorMap);\n}\n\nexport const clone = op({clone_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\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(f: () => T): Promise {\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 {\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 {\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> =\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 {\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 (``)\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>, 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>): 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 {\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 {\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):\n (manifest: WeightsManifestConfig, filePathPrefix?: string,\n weightNames?: string[]) => Promise {\n return async(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[]): Promise => {\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, getWeightSpecs} 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;\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 {\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 {\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 = getWeightSpecs(weightsManifest);\n\n const fetchURLs: string[] = [];\n const urlPromises: Array> = [];\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 reconstitutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n * Can be an absolute HTTP path (e.g.,\n * 'http://localhost:8000/model-upload)') or a relative path (e.g.,\n * './model-upload').\n * @param requestInit Request configurations to be used when sending\n * HTTP request to server using `fetch`. It can contain fields such as\n * `method`, `credentials`, `headers`, `mode`, etc. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n * for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n * following fields:\n * - weightPathPrefix Optional, this specifies the path prefix for weight\n * files, by default this is calculated from the path param.\n * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n * the `fetch` from node-fetch can be used here.\n * - onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function http(path: string, loadOptions?: LoadOptions): IOHandler {\n return new HTTPRequest(path, loadOptions);\n}\n\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nexport function browserHTTPRequest(\n path: string, loadOptions?: LoadOptions): IOHandler {\n return http(path, loadOptions);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers that pass through the in-memory ModelArtifacts format.\n */\n\nimport {IOHandler, IOHandlerSync, LoadHandler, ModelArtifacts, SaveHandler, SaveResult, TrainingConfig, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandlerSync {\n constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n load(): ModelArtifacts {\n return this.modelArtifacts;\n }\n}\n\nclass PassthroughSaver> {\n constructor(\n private readonly saveHandler: (artifacts: ModelArtifacts) => R) {}\n\n save(modelArtifacts: ModelArtifacts): R {\n return this.saveHandler(modelArtifacts);\n }\n}\n\nclass PassthroughAsync implements IOHandler {\n load?: LoadHandler;\n save?: SaveHandler;\n\n constructor(handler: IOHandlerSync) {\n if (handler.load) {\n this.load = () => Promise.resolve(handler.load());\n }\n if (handler.save) {\n this.save = (modelArtifacts: ModelArtifacts) =>\n Promise.resolve(handler.save(modelArtifacts));\n }\n }\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data. Optional.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs. Optional.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: ArrayBuffer, trainingConfig?: TrainingConfig): IOHandler {\n\n const args = arguments as unknown as Parameters;\n return new PassthroughAsync(fromMemorySync(...args));\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data. Optional.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs. Optional.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandlerSync` that simply loads the provided data.\n */\nexport function fromMemorySync(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: ArrayBuffer, trainingConfig?: TrainingConfig): IOHandlerSync {\n if (arguments.length === 1) {\n const isModelArtifacts =\n (modelArtifacts as ModelArtifacts).modelTopology != null ||\n (modelArtifacts as ModelArtifacts).weightSpecs != null;\n if (isModelArtifacts) {\n return new PassthroughLoader(modelArtifacts as ModelArtifacts);\n } else {\n // Legacy support: with only modelTopology.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({modelTopology: modelArtifacts as {}});\n }\n } else {\n // Legacy support.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({\n modelTopology: modelArtifacts as {},\n weightSpecs,\n weightData,\n trainingConfig\n });\n }\n}\n\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * promise that resolves to a `SaveResult`.\n */\nexport function withSaveHandler(\n saveHandler: (artifacts: ModelArtifacts) =>\n Promise): IOHandler {\n return new PassthroughSaver(saveHandler);\n}\n\n/**\n * Creates an IOHandlerSync that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * `SaveResult`.\n */\nexport function withSaveHandlerSync(\n saveHandler: (artifacts: ModelArtifacts) => SaveResult): IOHandlerSync {\n return new PassthroughSaver(saveHandler);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'abs');\n\n if ($x.dtype === 'complex64') {\n const inputs: ComplexAbsInputs = {x: $x};\n return ENGINE.runKernel(ComplexAbs, inputs as {} as NamedTensorMap);\n } else {\n const inputs: AbsInputs = {x: $x};\n return ENGINE.runKernel(Abs, inputs as {} as NamedTensorMap);\n }\n}\n\nexport const abs = op({abs_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Acos, AcosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes acos of the input `tf.Tensor` element-wise: `acos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.acos().print(); // or tf.acos(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction acos_(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_(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 {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_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'add');\n let $b = convertToTensor(b, 'b', 'add');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: AddInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Add, inputs as {} as NamedTensorMap);\n}\n\nexport const add = op({add_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(tensors: Array): T {\n util.assert(\n Array.isArray(tensors),\n () => 'The argument passed to tf.addN() must be a list of tensors');\n util.assert(\n tensors.length >= 1,\n () => `Must pass at least one tensor to tf.addN(), but got ` +\n `${tensors.length}`);\n\n const $tensors =\n tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN'));\n\n const firstTensor = $tensors[0];\n $tensors.forEach(t => {\n if (t.dtype !== firstTensor.dtype) {\n throw new Error(\n 'All tensors passed to tf.addN() must have the same dtype');\n }\n });\n\n $tensors.forEach(t => {\n if (!util.arraysEqual(t.shape, firstTensor.shape)) {\n throw new Error(\n 'All tensors passed to tf.addN() must have the same shape');\n }\n });\n\n const inputs: AddNInputs = $tensors;\n\n return ENGINE.runKernel(AddN, inputs as {} as NamedTensorMap);\n}\n\nexport const addN = op({addN_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {All, AllAttrs, AllInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical and of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.all().print(); // or tf.all(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.all(axis).print(); // or tf.all(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction all_(\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 a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.any().print(); // or tf.any(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.any(axis).print(); // or tf.any(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction any_(\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_(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_(x: Tensor|TensorLike, axis = 0): T {\n const $x = convertToTensor(x, 'x', 'argMin');\n\n const inputs: ArgMinInputs = {x: $x};\n const attrs: ArgMinAttrs = {axis};\n\n return ENGINE.runKernel(\n ArgMin, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const argMin = op({argMin_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asin, AsinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes asin of the input `tf.Tensor` element-wise: `asin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asin().print(); // or tf.asin(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asin_(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_(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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'atan');\n\n const inputs: AtanInputs = {x: $x};\n\n return ENGINE.runKernel(Atan, inputs as {} as NamedTensorMap);\n}\nexport const atan = op({atan_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan2, Atan2Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);\n * const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);\n *\n * tf.atan2(a, b).print()\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan2_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'atan2');\n let $b = convertToTensor(b, 'b', 'atan2');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: Atan2Inputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Atan2, inputs as {} as NamedTensorMap);\n}\n\nexport const atan2 = op({atan2_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atanh, AtanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:\n * `atanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.atanh().print(); // or tf.atanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atanh_(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 * as util from '../util';\n\ntype PadType = 'SAME'|'VALID'|'NUMBER'|'EXPLICIT';\n\n// For NHWC should be in the following form:\n// [[0, 0], [pad_top,pad_bottom], [pad_left, pad_right], [0, 0]]\n// For NCHW should be in the following form:\n// [[0, 0], [0, 0], [pad_top,pad_bottom], [pad_left, pad_right]]\n// Reference: https://www.tensorflow.org/api_docs/python/tf/nn/conv2d\nexport type ExplicitPadding =\n [[number, number], [number, number], [number, number], [number, number]];\n\nexport type PadInfo = {\n top: number,\n left: number,\n right: number,\n bottom: number,\n type: PadType\n};\n\nexport type PadInfo3D = {\n top: number,\n left: number,\n right: number,\n bottom: number,\n front: number,\n back: number,\n type: PadType\n};\n\n/**\n * Information about the forward pass of a convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv2DInfo = {\n batchSize: number,\n inHeight: number,\n inWidth: number,\n inChannels: number,\n outHeight: number,\n outWidth: number,\n outChannels: number,\n dataFormat: 'channelsFirst'|'channelsLast',\n strideHeight: number,\n strideWidth: number,\n dilationHeight: number,\n dilationWidth: number,\n filterHeight: number,\n filterWidth: number,\n effectiveFilterHeight: number,\n effectiveFilterWidth: number,\n padInfo: PadInfo,\n inShape: [number, number, number, number],\n outShape: [number, number, number, number],\n filterShape: [number, number, number, number]\n};\n\n/**\n *\n * @param inputShape Input tensor shape is of the following dimensions:\n * `[batch, height, width, inChannels]`.\n * @param filterShape The filter shape is of the following dimensions:\n * `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n * input tensor: `[strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat The data format of the input and output data.\n * Defaults to 'NHWC'.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.\n * Defaults to `[1, 1]`. If `dilations` is a single number, then\n * `dilationHeight == dilationWidth`.\n */\nexport function computeDilation2DInfo(\n inputShape: [number, number, number, number],\n filterShape: [number, number, number], strides: number|[number, number],\n pad: 'same'|'valid'|number, dataFormat: 'NHWC' = 'NHWC',\n dilations: number|[number, number]) {\n // `computerConv2DInfo` require filterShape to be in the dimension of:\n // `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have\n // outDepth, it should have the same depth as the input.\n // Input shape: [batch, height, width, inChannels]\n const inputChannels = inputShape[3];\n const $filterShape =\n [...filterShape, inputChannels] as [number, number, number, number];\n const $dataFormat = convertConv2DDataFormat(dataFormat);\n\n return computeConv2DInfo(\n inputShape, $filterShape, strides, dilations, pad,\n null /* roundingMode */, null /* depthWise */, $dataFormat);\n}\n\nexport function computePool2DInfo(\n inShape: [number, number, number, number],\n filterSize: [number, number]|number, strides: number|[number, number],\n dilations: number|[number, number],\n pad: 'same'|'valid'|number|ExplicitPadding,\n roundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n const [filterHeight, filterWidth] = parseTupleParam(filterSize);\n\n let filterShape: [number, number, number, number];\n if (dataFormat === 'channelsLast') {\n filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];\n } else if (dataFormat === 'channelsFirst') {\n filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n return computeConv2DInfo(\n inShape, filterShape, strides, dilations, pad, roundingMode, false,\n dataFormat);\n}\n\n/**\n * Computes the information for a forward pass of a pooling3D operation.\n */\nexport function computePool3DInfo(\n inShape: [number, number, number, number, number],\n filterSize: number|[number, number, number],\n strides: number|[number, number, number],\n dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n roundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): Conv3DInfo {\n const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);\n\n let filterShape: [number, number, number, number, number];\n let $dataFormat: 'channelsFirst'|'channelsLast';\n if (dataFormat === 'NDHWC') {\n $dataFormat = 'channelsLast';\n filterShape =\n [filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];\n } else if (dataFormat === 'NCDHW') {\n $dataFormat = 'channelsFirst';\n filterShape =\n [filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n return computeConv3DInfo(\n inShape, filterShape, strides, dilations, pad, false, $dataFormat,\n roundingMode);\n}\n\n/**\n * Computes the information for a forward pass of a convolution/pooling\n * operation.\n */\nexport function computeConv2DInfo(\n inShape: [number, number, number, number],\n filterShape: [number, number, number, number],\n strides: number|[number, number], dilations: number|[number, number],\n pad: 'same'|'valid'|number|ExplicitPadding,\n roundingMode?: 'floor'|'round'|'ceil', depthwise = false,\n dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];\n if (dataFormat === 'channelsLast') {\n [batchSize, inHeight, inWidth, inChannels] = inShape;\n } else if (dataFormat === 'channelsFirst') {\n [batchSize, inChannels, inHeight, inWidth] = inShape;\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n const [filterHeight, filterWidth, , filterChannels] = filterShape;\n const [strideHeight, strideWidth] = parseTupleParam(strides);\n const [dilationHeight, dilationWidth] = parseTupleParam(dilations);\n\n const effectiveFilterHeight =\n getEffectiveFilterSize(filterHeight, dilationHeight);\n const effectiveFilterWidth =\n getEffectiveFilterSize(filterWidth, dilationWidth);\n const {padInfo, outHeight, outWidth} = getPadAndOutInfo(\n pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight,\n effectiveFilterWidth, roundingMode, dataFormat);\n\n const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n let outShape: [number, number, number, number];\n if (dataFormat === 'channelsFirst') {\n outShape = [batchSize, outChannels, outHeight, outWidth];\n } else if (dataFormat === 'channelsLast') {\n outShape = [batchSize, outHeight, outWidth, outChannels];\n }\n\n return {\n batchSize,\n dataFormat,\n inHeight,\n inWidth,\n inChannels,\n outHeight,\n outWidth,\n outChannels,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n effectiveFilterHeight,\n effectiveFilterWidth,\n dilationHeight,\n dilationWidth,\n inShape,\n outShape,\n filterShape\n };\n}\n\n/**\n * Information about the forward pass of a 3D convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv3DInfo = {\n batchSize: number,\n inDepth: number,\n inHeight: number,\n inWidth: number,\n inChannels: number,\n outDepth: number,\n outHeight: number,\n outWidth: number,\n outChannels: number,\n dataFormat: 'channelsFirst'|'channelsLast',\n strideDepth: number,\n strideHeight: number,\n strideWidth: number,\n dilationDepth: number,\n dilationHeight: number,\n dilationWidth: number,\n filterDepth: number,\n filterHeight: number,\n filterWidth: number,\n effectiveFilterDepth: number,\n effectiveFilterHeight: number,\n effectiveFilterWidth: number,\n padInfo: PadInfo3D,\n inShape: [number, number, number, number, number],\n outShape: [number, number, number, number, number],\n filterShape: [number, number, number, number, number]\n};\n\n/**\n * Computes the information for a forward pass of a 3D convolution/pooling\n * operation.\n */\nexport function computeConv3DInfo(\n inShape: [number, number, number, number, number],\n filterShape: [number, number, number, number, number],\n strides: number|[number, number, number],\n dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n depthwise = false,\n dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast',\n roundingMode?: 'floor'|'round'|'ceil'): Conv3DInfo {\n let [batchSize, inDepth, inHeight, inWidth, inChannels] =\n [-1, -1, -1, -1, -1];\n if (dataFormat === 'channelsLast') {\n [batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;\n } else if (dataFormat === 'channelsFirst') {\n [batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n const [filterDepth, filterHeight, filterWidth, , filterChannels] =\n filterShape;\n const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);\n const [dilationDepth, dilationHeight, dilationWidth] =\n parse3TupleParam(dilations);\n\n const effectiveFilterDepth =\n getEffectiveFilterSize(filterDepth, dilationDepth);\n const effectiveFilterHeight =\n getEffectiveFilterSize(filterHeight, dilationHeight);\n const effectiveFilterWidth =\n getEffectiveFilterSize(filterWidth, dilationWidth);\n const {padInfo, outDepth, outHeight, outWidth} = get3DPadAndOutInfo(\n pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth,\n effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth,\n roundingMode);\n\n const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n let outShape: [number, number, number, number, number];\n if (dataFormat === 'channelsFirst') {\n outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];\n } else if (dataFormat === 'channelsLast') {\n outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];\n }\n\n return {\n batchSize,\n dataFormat,\n inDepth,\n inHeight,\n inWidth,\n inChannels,\n outDepth,\n outHeight,\n outWidth,\n outChannels,\n padInfo,\n strideDepth,\n strideHeight,\n strideWidth,\n filterDepth,\n filterHeight,\n filterWidth,\n effectiveFilterDepth,\n effectiveFilterHeight,\n effectiveFilterWidth,\n dilationDepth,\n dilationHeight,\n dilationWidth,\n inShape,\n outShape,\n filterShape\n };\n}\n\nfunction computeOutputShape2D(\n inShape: [number, number], fieldSize: number, stride: number,\n zeroPad?: number, roundingMode?: 'floor'|'round'|'ceil'): [number, number] {\n if (zeroPad == null) {\n zeroPad = computeDefaultPad(inShape, fieldSize, stride);\n }\n const inputRows = inShape[0];\n const inputCols = inShape[1];\n\n const outputRows =\n round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n const outputCols =\n round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n\n return [outputRows, outputCols];\n}\n\nfunction computeOutputShape4D(\n inShape: [number, number, number, number], 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/**\n * Check validity of pad when using dimRoundingMode.\n * @param opDesc A string of op description\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid` output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @throws unknown padding parameter\n */\nexport function checkPadOnDimRoundingMode(\n opDesc: string, pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil') {\n if (dimRoundingMode != null) {\n if (typeof pad === 'string') {\n throw Error(\n `Error in ${opDesc}: pad must be an integer when using ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n } else if (typeof pad === 'number') {\n util.assert(\n util.isInt(pad),\n () => `Error in ${opDesc}: pad must be an integer when using ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n } else if (typeof pad === 'object') {\n (pad as ExplicitPadding).forEach(p => {p.forEach(v =>{\n util.assert(\n util.isInt(v),\n () => `Error in ${opDesc}: pad must be an integer when using ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${v}.`);\n });\n });\n } else {\n throw Error(`Error in ${opDesc}: Unknown padding parameter: ${pad}`);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reshape, ReshapeAttrs, ReshapeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reshapes a `tf.Tensor` to a given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * If one component of shape is the special value -1, the size of that\n * dimension is computed so that the total size remains constant. In\n * particular, a shape of [-1] flattens into 1-D. At most one component of\n * shape can be -1.\n *\n * If shape is 1-D or higher, then the operation returns a tensor with shape\n * shape filled with the values of tensor. In this case, the number of\n * elements implied by shape must be the same as the number of elements in\n * tensor.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.reshape([2, 2]).print();\n * ```\n *\n * @param x The input tensor to be reshaped.\n * @param shape An array of integers defining the output tensor shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction reshape_(\n x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor {\n const $x = convertToTensor(x, 'x', 'reshape', 'string_or_numeric');\n\n const inputs: ReshapeInputs = {x: $x};\n const attrs: ReshapeAttrs = {shape};\n return ENGINE.runKernel(\n Reshape, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\nexport const reshape = op({reshape_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool, AvgPoolAttrs, AvgPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D average pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction avgPool_(\n x: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'avgPool', 'float32');\n const dilations = 1;\n\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);\n conv_util.checkPadOnDimRoundingMode('avgPool', pad, dimRoundingMode);\n const inputs: AvgPoolInputs = {x: x4D};\n const attrs: AvgPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res = ENGINE.runKernel(\n AvgPool, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n res = cast(res, $x.dtype);\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n\n return res;\n}\n\nexport const avgPool = op({avgPool_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {checkPadOnDimRoundingMode} from './conv_util';\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_(\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 checkPadOnDimRoundingMode('avgPool3d', pad, dimRoundingMode);\n const inputs: AvgPool3DInputs = {x: x5D};\n const attrs:\n AvgPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res = ENGINE.runKernel(\n AvgPool3D, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n res = cast(res, x5D.dtype);\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n\n return res;\n}\n\nexport const avgPool3d = op({avgPool3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Concat, ConcatAttrs, ConcatInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {clone} from './clone';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor`s along a given axis.\n *\n * The tensors ranks and types must match, and their sizes must match in all\n * dimensions except `axis`.\n *\n * Also available are stricter rank-specific methods that assert that\n * `tensors` are of the given rank:\n * - `tf.concat1d`\n * - `tf.concat2d`\n * - `tf.concat3d`\n * - `tf.concat4d`\n *\n * Except `tf.concat1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * a.concat(b).print(); // or a.concat(b)\n * ```\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.concat([a, b, c]).print();\n * ```\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [10, 20]]);\n * const b = tf.tensor2d([[3, 4], [30, 40]]);\n * const axis = 1;\n * tf.concat([a, b], axis).print();\n * ```\n * @param tensors A list of tensors to concatenate.\n * @param axis The axis to concatenate along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction concat_(tensors: Array, axis = 0): T {\n assert(tensors.length >= 1, () => 'Pass at least one tensor to concat');\n\n const $tensors =\n convertToTensorArray(tensors, 'tensors', 'concat', 'string_or_numeric');\n\n if ($tensors[0].dtype === 'complex64') {\n $tensors.forEach(tensor => {\n if (tensor.dtype !== 'complex64') {\n throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${tensor.dtype}. `);\n }\n });\n }\n\n if ($tensors.length === 1) {\n return clone($tensors[0]);\n }\n\n const inputs: ConcatInputs = $tensors;\n const attr: ConcatAttrs = {axis};\n\n return ENGINE.runKernel(\n Concat, inputs as {} as NamedTensorMap, attr as {} as NamedAttrMap);\n}\n\nexport const concat = op({concat_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike, transposeA = false,\n transposeB = false): T {\n let $a = convertToTensor(a, 'a', 'matMul');\n let $b = convertToTensor(b, 'b', 'matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: BatchMatMulInputs = {a: $a, b: $b};\n const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n return ENGINE.runKernel(\n BatchMatMul, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const matMul = op({matMul_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'mul');\n let $b = convertToTensor(b, 'b', 'mul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: MultiplyInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Multiply, inputs as {} as NamedTensorMap);\n}\nexport const mul = op({mul_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sigmoid', 'float32');\n\n const inputs: SigmoidInputs = {x: $x};\n\n return ENGINE.runKernel(Sigmoid, inputs as {} as NamedTensorMap);\n}\nexport const sigmoid = op({sigmoid_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Slice, SliceAttrs, SliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a slice from a `tf.Tensor` starting at coordinates `begin`\n * and is of size `size`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `x` is of the given rank:\n * - `tf.slice1d`\n * - `tf.slice2d`\n * - `tf.slice3d`\n * - `tf.slice4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.slice([1], [2]).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * x.slice([1, 0], [1, 2]).print();\n * ```\n * @param x The input `tf.Tensor` to slice from.\n * @param begin The coordinates to start the slice from. The length can be\n * less than the rank of x - the rest of the axes will have implicit 0 as\n * start. Can also be a single number, in which case it specifies the\n * first axis.\n * @param size The size of the slice. The length can be less than the rank of\n * x - the rest of the axes will have implicit -1. A value of -1 requests\n * the rest of the dimensions in the axis. Can also be a single number,\n * in which case it specifies the size of the first axis.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction slice_>(\n x: T|TensorLike, begin: number|number[], size?: number|number[]): T {\n const $x = convertToTensor(x, 'x', 'slice', 'string_or_numeric');\n\n if ($x.rank === 0) {\n throw new Error('Slicing scalar is not possible');\n }\n\n const inputs: SliceInputs = {x: $x};\n const attrs: SliceAttrs = {begin, size};\n\n return ENGINE.runKernel(\n Slice, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const slice = op({slice_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tanh, TanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, 70]);\n *\n * x.tanh().print(); // or tf.tanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tanh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'tanh', 'float32');\n\n const inputs: TanhInputs = {x: $x};\n\n return ENGINE.runKernel(Tanh, inputs as {} as NamedTensorMap);\n}\nexport const tanh = op({tanh_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {add} from './add';\nimport {concat} from './concat';\nimport {matMul} from './mat_mul';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {slice} from './slice';\nimport {tanh} from './tanh';\n\n/**\n * Computes the next state and output of a BasicLSTMCell.\n *\n * Returns `[newC, newH]`.\n *\n * Derived from tf.contrib.rnn.BasicLSTMCell.\n *\n * @param forgetBias Forget bias for the cell.\n * @param lstmKernel The weights for the cell.\n * @param lstmBias The bias for the cell.\n * @param data The input to the cell.\n * @param c Previous cell state.\n * @param h Previous cell output.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction basicLSTMCell_(\n forgetBias: Scalar|TensorLike, lstmKernel: Tensor2D|TensorLike,\n lstmBias: Tensor1D|TensorLike, data: Tensor2D|TensorLike,\n c: Tensor2D|TensorLike, h: Tensor2D|TensorLike): [Tensor2D, Tensor2D] {\n const $forgetBias =\n convertToTensor(forgetBias, 'forgetBias', 'basicLSTMCell');\n const $lstmKernel =\n convertToTensor(lstmKernel, 'lstmKernel', 'basicLSTMCell');\n const $lstmBias = convertToTensor(lstmBias, 'lstmBias', 'basicLSTMCell');\n const $data = convertToTensor(data, 'data', 'basicLSTMCell');\n const $c = convertToTensor(c, 'c', 'basicLSTMCell');\n const $h = convertToTensor(h, 'h', 'basicLSTMCell');\n\n const combined = concat([$data, $h], 1);\n const weighted = matMul(combined, $lstmKernel);\n const res: Tensor2D = add(weighted, $lstmBias);\n\n // i = input_gate, j = new_input, f = forget_gate, o = output_gate\n const batchSize = res.shape[0];\n const sliceCols = res.shape[1] / 4;\n const sliceSize: [number, number] = [batchSize, sliceCols];\n const i = slice(res, [0, 0], sliceSize);\n const j = slice(res, [0, sliceCols], sliceSize);\n const f = slice(res, [0, sliceCols * 2], sliceSize);\n const o = slice(res, [0, sliceCols * 3], sliceSize);\n\n const newC: Tensor2D =\n add(mul(sigmoid(i), tanh(j)),\n mul($c, sigmoid(add($forgetBias, f)) as Tensor2D));\n const newH: Tensor2D = mul(tanh(newC), sigmoid(o));\n return [newC, newH];\n}\n\nexport const basicLSTMCell = op({basicLSTMCell_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of\n * shape `blockShape + [batch]`, interleaves these blocks back into the grid\n * defined by the spatial dimensions `[1, ..., M]`, to obtain a result with\n * the same rank as the input. The spatial dimensions of this intermediate\n * result are then optionally cropped according to `crops` to produce the\n * output. This is the reverse of `tf.spaceToBatchND`. See below for a precise\n * description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);\n * const blockShape = [2, 2];\n * const crops = [[0, 0], [0, 0]];\n *\n * x.batchToSpaceND(blockShape, crops).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.\n * `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input\n * dimension `i + 1`, which corresponds to spatial dimension `i`. It is required\n * that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,\n * blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,\n * x.shape[N-1]]`\n *\n * 2. Permute dimensions of `reshaped` to produce `permuted` of shape `[batch /\n * prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`\n * according to `crops` to produce the output of shape: `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],\n * ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -\n * crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction batchToSpaceND_(\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 */\n\nimport {ENGINE} from '../engine';\nimport {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {xAs4D} from './batchnorm_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Batch normalization.\n *\n * As described in\n * [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).\n *\n * Mean, variance, scale, and offset can be of two shapes:\n * - The same shape as the input.\n * - In the common case, the depth dimension is the last dimension of x, so\n * the values would be a `tf.Tensor1D` of shape [depth].\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that parameters passed are of given rank\n * - `tf.batchNorm2d`\n * - `tf.batchNorm3d`\n * - `tf.batchNorm4d`\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction batchNorm_(\n x: Tensor|TensorLike, mean: Tensor|Tensor1D|TensorLike,\n variance: Tensor|Tensor1D|TensorLike,\n offset?: Tensor|Tensor1D|TensorLike,\n scale?: Tensor|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor {\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|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor|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;\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(x: Tensor) {\n let x4D: Tensor4D;\n if (x.rank === 0 || x.rank === 1) {\n x4D = reshape(x, [1, 1, 1, x.size]);\n } else if (x.rank === 2) {\n x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);\n } else if (x.rank === 3) {\n x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n } else {\n x4D = x as Tensor4D;\n }\n\n return x4D;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 2D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm2d_(\n x: Tensor2D|TensorLike, mean: Tensor2D|Tensor1D|TensorLike,\n variance: Tensor2D|Tensor1D|TensorLike,\n offset?: Tensor2D|Tensor1D|TensorLike, scale?: Tensor2D|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor2D {\n const $x = convertToTensor(x, 'x', 'batchNorm');\n const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n let $scale: Tensor2D|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor2D|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n util.assert(\n $x.rank === 2,\n () => `Error in batchNorm2D: x must be rank 2 but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $mean.rank === 2 || $mean.rank === 1,\n () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but ` +\n `got rank ${$mean.rank}.`);\n util.assert(\n $variance.rank === 2 || $variance.rank === 1,\n () => `Error in batchNorm2D: variance must be rank 2 or rank 1 ` +\n `but got rank ${$variance.rank}.`);\n if ($scale != null) {\n util.assert(\n $scale.rank === 2 || $scale.rank === 1,\n () => `Error in batchNorm2D: scale must be rank 2 or rank 1 ` +\n `but got rank ${$scale.rank}.`);\n }\n if ($offset != null) {\n util.assert(\n $offset.rank === 2 || $offset.rank === 1,\n () => `Error in batchNorm2D: offset must be rank 2 or rank 1 ` +\n `but got rank ${$offset.rank}.`);\n }\n\n return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm2d = op({batchNorm2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 3D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm3d_(\n x: Tensor3D|TensorLike, mean: Tensor3D|Tensor1D|TensorLike,\n variance: Tensor3D|Tensor1D|TensorLike,\n offset?: Tensor3D|Tensor1D|TensorLike, scale?: Tensor3D|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor3D {\n const $x = convertToTensor(x, 'x', 'batchNorm');\n const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n let $scale: Tensor3D|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor3D|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n util.assert(\n $x.rank === 3,\n () => `Error in batchNorm3D: x must be rank 3 but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $mean.rank === 3 || $mean.rank === 1,\n () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but ` +\n `got rank ${$mean.rank}.`);\n util.assert(\n $variance.rank === 3 || $variance.rank === 1,\n () => `Error in batchNorm3D: variance must be rank 3 or rank 1 ` +\n `but got rank ${$variance.rank}.`);\n if ($scale != null) {\n util.assert(\n $scale.rank === 3 || $scale.rank === 1,\n () => `Error in batchNorm3D: scale must be rank 3 or rank 1 ` +\n `but got rank ${$scale.rank}.`);\n }\n if ($offset != null) {\n util.assert(\n $offset.rank === 3 || $offset.rank === 1,\n () => `Error in batchNorm3D: offset must be rank 3 or rank 1 ` +\n `but got rank ${$offset.rank}.`);\n }\n\n return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm3d = op({batchNorm3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 4D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm4d_(\n x: Tensor4D|TensorLike, mean: Tensor4D|Tensor1D|TensorLike,\n variance: Tensor4D|Tensor1D|TensorLike,\n offset?: Tensor4D|Tensor1D|TensorLike, scale?: Tensor4D|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor4D {\n const $x = convertToTensor(x, 'x', 'batchNorm');\n const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n let $scale: Tensor4D|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor4D|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n util.assert(\n $x.rank === 4,\n () => `Error in batchNorm4D: x must be rank 4 but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $mean.rank === 4 || $mean.rank === 1,\n () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but ` +\n `got rank ${$mean.rank}.`);\n util.assert(\n $variance.rank === 4 || $variance.rank === 1,\n () => `Error in batchNorm4D: variance must be rank 4 or rank 1 ` +\n `but got rank ${$variance.rank}.`);\n if ($scale != null) {\n util.assert(\n $scale.rank === 4 || $scale.rank === 1,\n () => `Error in batchNorm4D: scale must be rank 4 or rank 1 ` +\n `but got rank ${$scale.rank}.`);\n }\n if ($offset != null) {\n util.assert(\n $offset.rank === 4 || $offset.rank === 1,\n () => `Error in batchNorm4D: offset must be rank 4 or rank 1 ` +\n `but got rank ${$offset.rank}.`);\n }\n return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm4d = op({batchNorm4d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Bincount, BincountAttrs, BincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1.\n * @param weights The weights tensor, must have the same shape as x, or a\n * length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction bincount_(\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 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { NamedTensorMap } from '../tensor_types';\nimport { ENGINE } from '../engine';\nimport { BroadcastArgs, BroadcastArgsInputs } from '../kernel_names';\nimport { Tensor } from '../tensor';\nimport { convertToTensor } from '../tensor_util_env';\nimport { Rank, TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Return the shape of s0 op s1 with broadcast.\n *\n * compute r0, the broadcasted shape as a tensor.\n * s0, s1 and r0 are all integer vectors.\n *\n * This function returns the shape of the result of an operation between\n * two tensors of size s0 and s1 performed with broadcast.\n *\n * @param s0 A tensor representing a shape\n * @param s1 A tensor representing a shape\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastArgs_(\n s0: Tensor | TensorLike, s1: Tensor | TensorLike): Tensor {\n const shape1Input = convertToTensor(s0, 's0', 'broadcastArgs', 'int32');\n const shape2Input = convertToTensor(s1, 's1', 'broadcastArgs', 'int32');\n\n if (shape1Input.rank !== 1) {\n throw new Error(\n 'broadcastArgs(): first input must be a vector (rank=1). ' +\n `Has rank ${shape1Input.rank}`);\n }\n\n if (shape2Input.rank !== 1) {\n throw new Error(\n 'broadcastArgs(): second input must be a vector (rank=1). ' +\n `Has rank ${shape2Input.rank}`);\n }\n\n const inputs: BroadcastArgsInputs = { s0: shape1Input, s1: shape2Input };\n return ENGINE.runKernel(BroadcastArgs, inputs as {} as NamedTensorMap);\n}\n\nexport const broadcastArgs = op({ broadcastArgs_ });\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\n\nimport {clone} from './clone';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Broadcast an array to a compatible shape NumPy-style.\n *\n * The tensor's shape is compared to the broadcast shape from end to beginning.\n * Ones are prepended to the tensor's shape until it has the same length as\n * the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is\n * already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then\n * the input tensor is tiled N times along that axis (using tf.tile).\n *\n * @param input The tensor that is to be broadcasted.\n * @param shape The input is to be broadcast to this shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastTo_(\n x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor {\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;\n }\n\n // TODO call broadcastTo kernel directly once backends implement broadcstTo\n const inputs: TileInputs = {x: input};\n const attrs: TileAttrs = {reps};\n return ENGINE.runKernel(\n Tile, inputs as {} as NamedTensorMap, attrs as unknown as NamedAttrMap);\n}\n\nexport const broadcastTo = op({broadcastTo_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Ceil, CeilInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.ceil().print(); // or tf.ceil(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction ceil_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'ceil', 'float32');\n\n const inputs: CeilInputs = {x: $x};\n return ENGINE.runKernel(Ceil, inputs as {} as NamedTensorMap);\n}\nexport const ceil = op({ceil_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Fill, FillAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\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(\n shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor {\n const attrs: FillAttrs = {shape, value, dtype};\n\n return ENGINE.runKernel(Fill, {}, attrs as {} as NamedAttrMap);\n}\n\nexport {fill};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {fill} from './fill';\n\nimport {op} from './operation';\n\n/**\n * Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)\n * ```\n * @param x The input tensor.\n * @param clipValueMin Lower bound of range to be clipped to.\n * @param clipValueMax Upper bound of range to be clipped to.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction clipByValue_(\n x: T|TensorLike, clipValueMin: number, clipValueMax: number): T {\n const $x = convertToTensor(x, 'x', 'clipByValue');\n util.assert(\n (clipValueMin <= clipValueMax),\n () => `Error in clip: min (${clipValueMin}) must be ` +\n `less than or equal to max (${clipValueMax}).`);\n\n if (clipValueMin === clipValueMax) {\n return fill($x.shape, clipValueMin, $x.dtype) as T;\n }\n\n const inputs: ClipByValueInputs = {x: $x};\n const attrs: ClipByValueAttrs = {clipValueMin, clipValueMax};\n\n return ENGINE.runKernel(\n ClipByValue, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const clipByValue = op({clipByValue_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(3) = |r1, g1, b1|\n * B: shape(2) = |r2, g2|\n * C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @return The concatenated array.\n */\nfunction concat1d_(tensors: Array): Tensor1D {\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, 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, 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, axis: number): Tensor4D {\n return concat(tensors, axis);\n}\n\nexport const concat4d = op({concat4d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2D, Conv2DAttrs, Conv2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 2D convolution over the input x.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2d_(\n x: T|TensorLike, filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in conv2d: filter must be rank 4, but got rank ` +\n `${$filter.rank}.`);\n conv_util.checkPadOnDimRoundingMode('conv2d', pad, dimRoundingMode);\n const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n util.assert(\n inDepth === $filter.shape[2],\n () => `Error in conv2d: depth of input (${inDepth}) must match ` +\n `input depth for filter ${$filter.shape[2]}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const inputs: Conv2DInputs = {x: x4D, filter: $filter};\n const attrs:\n Conv2DAttrs = {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv2D, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const conv2d = op({conv2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D, Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 1D convolution over the input x.\n *\n * @param x The input tensor, of rank 3 or rank 2, of shape\n * `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.\n * @param filter The filter, rank 3, of shape\n * `[filterWidth, inDepth, outDepth]`.\n * @param stride The number of entries by which the filter is moved right at\n * each step.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from \"NWC\", \"NCW\". Defaults to \"NWC\",\n * the data is stored in the order of [batch, in_width, in_channels]. Only\n * \"NWC\" is currently supported.\n * @param dilation The dilation rate in which we sample input values in\n * atrous convolution. Defaults to `1`. If it is greater than 1, then\n * stride must be `1`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv1d_(\n x: T|TensorLike, filter: Tensor3D|TensorLike, stride: number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NWC'|'NCW' = 'NWC', dilation = 1,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'conv1d');\n const $filter = convertToTensor(filter, 'filter', 'conv1d');\n\n let x3D = $x as Tensor3D;\n let reshapedTo3D = false;\n if ($x.rank === 2) {\n reshapedTo3D = true;\n x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);\n }\n\n util.assert(\n x3D.rank === 3,\n () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);\n util.assert(\n $filter.rank === 3,\n () => `Error in conv1d: filter must be rank 3, but got rank ` +\n `${$filter.rank}.`);\n conv_util.checkPadOnDimRoundingMode('conv1d', pad, dimRoundingMode);\n util.assert(\n x3D.shape[2] === $filter.shape[1],\n () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +\n `input depth for filter ${$filter.shape[1]}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(stride, dilation),\n () => 'Error in conv1D: Either stride or dilation must be 1. ' +\n `Got stride ${stride} and dilation '${dilation}'`);\n util.assert(\n dataFormat === 'NWC',\n () => `Error in conv1d: got dataFormat of ${\n dataFormat} but only NWC is currently supported.`);\n\n const filter4D = reshape(\n $filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);\n const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);\n const strides: [number, number] = [1, stride];\n const dilations: [number, number] = [1, dilation];\n\n const conv2dDataFormat = 'NHWC';\n\n const res = conv2d(\n (input4D as Tensor4D), (filter4D as Tensor4D), strides, pad,\n conv2dDataFormat, dilations, dimRoundingMode);\n\n if (reshapedTo3D) {\n return reshape(res, [res.shape[2], res.shape[3]]) as T;\n }\n\n return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]) as T;\n}\n\nexport const conv1d = op({conv1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 2D convolution.\n *\n * @param xShape The shape of the input: [batch, height, width, inDepth].\n * If length of 3, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 4 or rank 3 of shape\n * `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction conv2DBackpropInput_(\n xShape: [number, number, number, number]|[number, number, number], dy: T,\n filter: Tensor4D, strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n util.assert(\n xShape.length === dy.rank,\n () => `Length of inShape ` +\n `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n let xShape4D = xShape as [number, number, number, number];\n let dy4D = dy as Tensor4D;\n let reshapedTo4D = false;\n if (dy.rank === 3) {\n reshapedTo4D = true;\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n xShape4D = [1, xShape[0], xShape[1], xShape[2]];\n }\n\n util.assert(\n xShape4D.length === 4,\n () =>\n `Error in conv2dDerInput: inShape must be length 4, but got length ` +\n `${xShape4D.length}.`);\n util.assert(\n dy4D.rank === 4,\n () => `Error in conv2dDerInput: dy must be rank 4, but got ` +\n `rank ${dy4D.rank}`);\n util.assert(\n filter.rank === 4,\n () => `Error in conv2dDerInput: filter must be rank 4, but got ` +\n `rank ${filter.rank}`);\n const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];\n const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n util.assert(\n inDepth === filter.shape[2],\n () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +\n `match input depth for filter ${filter.shape[2]}.`);\n util.assert(\n outDepth === filter.shape[3],\n () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +\n `match output depth for filter ${filter.shape[3]}.`);\n conv_util.checkPadOnDimRoundingMode('conv2dDerInput', pad, dimRoundingMode);\n const inputs: Conv2DBackpropInputInputs = {dy: dy4D, filter};\n const attrs: Conv2DBackpropInputAttrs =\n {strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv2DBackpropInput, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const conv2DBackpropInput = op({conv2DBackpropInput_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv2DBackpropInput} from './conv2d_backprop_input';\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 2D convolution of an image, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 4 or rank 3, of shape\n * `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, outDepth, inDepth]`.\n * `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 4 or rank 3:\n * `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.\n * @param strides The strides of the original convolution:\n * `[strideHeight, strideWidth]`.\n * @param pad The type of padding algorithm used in the non-transpose version\n * of the op.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2dTranspose_(\n x: T|TensorLike, filter: Tensor4D|TensorLike,\n outputShape: [number, number, number, number]|[number, number, number],\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'conv2dTranspose');\n const $filter = convertToTensor(filter, 'filter', 'conv2dTranspose');\n\n return conv2DBackpropInput(\n outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);\n}\n\nexport const conv2dTranspose = op({conv2dTranspose_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3D, Conv3DAttrs, Conv3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {eitherStridesOrDilationsAreOne} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 3D convolution over the input x.\n *\n * @param x The input tensor, of rank 5 or rank 4, of shape\n * `[batch, depth, height, width, channels]`. If rank 4,\n * batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n * `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.\n * inChannels must match between input and filter.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n * \"NDHWC\". Specify the data format of the input and output data. With the\n * default format \"NDHWC\", the data is stored in the order of: [batch,\n * depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationDepth, dilationHeight,\n * dilationWidth]` in which we sample input values across the height\n * and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.\n * If `dilations` is a single number, then\n * `dilationDepth == dilationHeight == dilationWidth`. If it is greater\n * than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3d_(\n x: T|TensorLike, filter: Tensor5D|TensorLike,\n strides: [number, number, number]|number, pad: 'valid'|'same',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC',\n dilations: [number, number, number]|number = [1, 1, 1]): T {\n const $x = convertToTensor(x, 'x', 'conv3d');\n const $filter = convertToTensor(filter, 'filter', 'conv3d');\n\n let x5D = $x as Tensor5D;\n let reshapedTo5D = false;\n\n if ($x.rank === 4) {\n reshapedTo5D = true;\n x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n }\n util.assert(\n x5D.rank === 5,\n () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);\n util.assert(\n $filter.rank === 5,\n () => `Error in conv3d: filter must be rank 5, but got rank ` +\n `${$filter.rank}.`);\n util.assert(\n x5D.shape[4] === $filter.shape[3],\n () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +\n `input depth for filter ${$filter.shape[3]}.`);\n util.assert(\n eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in conv3D: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n util.assert(\n dataFormat === 'NDHWC',\n () => `Error in conv3d: got dataFormat of ${\n dataFormat} but only NDHWC is currently supported.`);\n\n const inputs: Conv3DInputs = {x: x5D, filter: $filter};\n\n const attrs: Conv3DAttrs = {strides, pad, dataFormat, dilations};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv3D, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n return res;\n}\n\nexport const conv3d = op({conv3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 3D convolution.\n *\n * @param xShape The shape of the input: [batch, depth, height, width,\n * in_channels]. If length of 4, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 5 or rank 4 of shape\n * `[batch, outDepth, outHeight, outWidth, in_channels]`.\n * If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n * `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n */\nfunction conv3DBackpropInput_(\n xShape:\n [number, number, number, number,\n number]|[number, number, number, number],\n dy: T, filter: Tensor5D, strides: [number, number, number]|number,\n pad: 'valid'|'same'): T {\n util.assert(\n xShape.length === dy.rank,\n () => `Length of inShape ` +\n `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n let xShape5D = xShape as [number, number, number, number, number];\n let dy5D = dy as Tensor5D;\n let reshapedTo5D = false;\n if (dy.rank === 4) {\n reshapedTo5D = true;\n dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);\n xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];\n }\n\n const inDepth = xShape5D[4];\n const outDepth = dy5D.shape[4];\n util.assert(\n xShape5D.length === 5,\n () =>\n `Error in conv3dDerInput: inShape must be length 5, but got length ` +\n `${xShape5D.length}.`);\n util.assert(\n dy5D.rank === 5,\n () => `Error in conv3dDerInput: dy must be rank 5, but got ` +\n `rank ${dy5D.rank}`);\n util.assert(\n filter.rank === 5,\n () => `Error in conv3dDerInput: filter must be rank 5, but got ` +\n `rank ${filter.rank}`);\n util.assert(\n inDepth === filter.shape[3],\n () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +\n `match input depth for filter ${filter.shape[3]}.`);\n util.assert(\n outDepth === filter.shape[4],\n () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +\n `match output depth for filter ${filter.shape[4]}.`);\n\n const inputs: Conv3DBackpropInputV2Inputs = {dy: dy5D, filter};\n\n const attrs:\n Conv3DBackpropInputV2Attrs = {pad, strides, inputShape: xShape5D};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv3DBackpropInputV2, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n return res;\n}\n\nexport const conv3DBackpropInput = op({conv3DBackpropInput_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv3DBackpropInput} from './conv3d_backprop_input';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 3D convolution of a volume, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 5 or rank 4, of shape\n * `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n * `[depth, filterHeight, filterWidth, outDepth, inDepth]`.\n * `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 5 or rank 4:\n * `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is\n * assumed.\n * @param strides The strides of the original convolution:\n * `[strideDepth, strideHeight, strideWidth]`.\n * @param pad The type of padding algorithm used in the non-transpose version\n * of the op.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3dTranspose_(\n x: T|TensorLike, filter: Tensor5D|TensorLike,\n outputShape:\n [number, number, number, number,\n number]|[number, number, number, number],\n strides: [number, number, number]|number, pad: 'valid'|'same'): T {\n const $x = convertToTensor(x, 'x', 'conv3dTranspose');\n const $filter = convertToTensor(filter, 'filter', 'conv3dTranspose');\n\n return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);\n}\n\nexport const conv3dTranspose = op({conv3dTranspose_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cos, CosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes cos of the input `tf.Tensor` element-wise: `cos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.cos().print(); // or tf.cos(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cos_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'cos', 'float32');\n\n const inputs: CosInputs = {x: $x};\n\n return ENGINE.runKernel(Cos, inputs as {} as NamedTensorMap);\n}\nexport const cos = op({cos_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cosh, CoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.cosh().print(); // or tf.cosh(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cosh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'cosh', 'float32');\n const inputs: CoshInputs = {x: $x};\n\n return ENGINE.runKernel(Cosh, inputs as {} as NamedTensorMap);\n}\nexport const cosh = op({cosh_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { ENGINE } from '../engine';\nimport { Cumprod, CumprodAttrs, CumprodInputs } from '../kernel_names';\nimport { NamedAttrMap } from '../kernel_registry';\nimport { Tensor } from '../tensor';\nimport { NamedTensorMap } from '../tensor_types';\nimport { convertToTensor } from '../tensor_util_env';\nimport { TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Computes the cumulative product of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumprod().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumprod().print();\n * ```\n *\n * @param x The input tensor to cumulatively multiply.\n * @param axis The axis along which to multiply. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative product. Optional.\n * Defaults to false. If set to true then the product of each tensor entry\n * does not include its own value, but only the values previous to it\n * along the specified axis.\n * @param reverse Whether to multiply in the opposite direction. Optional.\n * Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumprod_(\n x: Tensor | TensorLike,\n axis = 0,\n exclusive = false,\n reverse = false\n): T {\n const $x = convertToTensor(x, 'x', 'cumprod');\n\n const inputs: CumprodInputs = { x: $x };\n const attrs: CumprodAttrs = { axis, exclusive, reverse };\n\n return ENGINE.runKernel(\n Cumprod,\n inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap\n );\n}\n\nexport const cumprod = op({ cumprod_ });\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cumsum, CumsumAttrs, CumsumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the cumulative sum of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumsum().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumsum().print();\n * ```\n *\n * @param x The input tensor to be summed.\n * @param axis The axis along which to sum. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative sum. Optional.\n * Defaults to false. If set to true then the sum of each tensor entry\n * does not include its own value, but only the values previous to it\n * along the specified axis.\n * @param reverse Whether to sum in the opposite direction. Optional.\n * Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumsum_(\n x: Tensor|TensorLike, axis = 0, exclusive = false, reverse = false): T {\n const $x = convertToTensor(x, 'x', 'cumsum');\n\n const inputs: CumsumInputs = {x: $x};\n const attrs: CumsumAttrs = {axis, exclusive, reverse};\n\n return ENGINE.runKernel(\n Cumsum, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const cumsum = op({cumsum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1 or rank 2.\n * @param weights The weights tensor, must have the same shape as x, or a\n * length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n * @param binaryOutput Optional. Whether the kernel should count the appearance\n * or number of occurrences. Defaults to False.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction denseBincount_(\n x: T|TensorLike, weights: T|TensorLike, size: number,\n binaryOutput = false): T {\n const $x = convertToTensor(x, 'x', 'denseBincount');\n const $weights = convertToTensor(weights, 'weights', 'denseBincount');\n\n util.assert(\n $x.dtype === 'int32',\n () => `Error in denseBincount: input ` +\n `dtype must be int32, but got ${$x.dtype}`);\n util.assert(\n $x.rank <= 2,\n () => `Error in denseBincount: input must be at most rank 2, but got ` +\n `rank ${$x.rank}.`);\n util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n util.assert(\n $weights.size === $x.size || $weights.size === 0,\n () =>\n `Error in denseBincount: weights must have the same shape as x or ` +\n `0-length, but got x shape: ${$x.shape}, weights shape: ` +\n `${$weights.shape}.`);\n\n const inputs: DenseBincountInputs = {x: $x, weights: $weights};\n const attrs: DenseBincountAttrs = {size, binaryOutput};\n\n return ENGINE.runKernel(\n DenseBincount, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const denseBincount = op({denseBincount_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Rearranges data from depth into blocks of spatial data. More specifically,\n * this op outputs a copy of the input tensor where values from the `depth`\n * dimension are moved in spatial blocks to the `height` and `width` dimensions.\n * The attr `blockSize` indicates the input block size and how the data is\n * moved.\n *\n * - Chunks of data of size `blockSize * blockSize` from depth are rearranged\n * into non-overlapping blocks of size `blockSize x blockSize`\n *\n * - The width the output tensor is `inputWidth * blockSize`, whereas the\n * height is `inputHeight * blockSize`\n *\n * - The Y, X coordinates within each block of the output image are determined\n * by the high order component of the input channel index\n *\n * - The depth of the input tensor must be divisible by `blockSize *\n * blockSize`\n *\n * The `dataFormat` attr specifies the layout of the input and output tensors\n * with the following options: \"NHWC\": [ `batch, height, width, channels` ]\n * \"NCHW\": [ `batch, channels, height, width` ]\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);\n * const blockSize = 2;\n * const dataFormat = \"NHWC\";\n *\n * tf.depthToSpace(x, blockSize, dataFormat).print();\n * ```\n *\n * @param x The input tensor of rank 4\n * @param blockSIze An `int` that is `>= 2`. The size of the spatial block\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to \"NHWC\"\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction depthToSpace_(\n x: Tensor4D|TensorLike4D, blockSize: number,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC'): Tensor4D {\n const $x = convertToTensor(x, 'x', 'depthToSpace', 'float32') as Tensor4D;\n\n const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];\n const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];\n const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];\n\n util.assert(\n blockSize > 1,\n () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n util.assert(\n inputHeight * blockSize >= 0,\n () => `Negative dimension size caused by overflow when multiplying\n ${inputHeight} and ${blockSize} for depthToSpace with input shape\n ${$x.shape}`);\n\n util.assert(\n inputWidth * blockSize >= 0,\n () => `Negative dimension size caused by overflow when multiplying\n ${inputWidth} and ${blockSize} for depthToSpace with input shape\n ${$x.shape}`);\n\n util.assert(\n (inputDepth % (blockSize * blockSize) === 0),\n () => `Dimension size must be evenly divisible by ${\n blockSize * blockSize} but is ${\n inputDepth} for depthToSpace with input shape ${$x.shape}`);\n\n const inputs: DepthToSpaceInputs = {x: $x};\n const attrs: DepthToSpaceAttrs = {blockSize, dataFormat};\n\n return ENGINE.runKernel(\n DepthToSpace, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const depthToSpace = op({depthToSpace_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Depthwise 2D convolution.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n * https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction depthwiseConv2d_(\n x: T|TensorLike, filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n const $filter =\n convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in depthwiseConv2d: input must be rank 4, but got ` +\n `rank ${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +\n `${$filter.rank}.`);\n const inChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n util.assert(\n inChannels === $filter.shape[2],\n () => `Error in depthwiseConv2d: number of input channels ` +\n `(${inChannels}) must match the inChannels dimension in ` +\n `filter ${$filter.shape[2]}.`);\n conv_util.checkPadOnDimRoundingMode('depthwiseConv2d', pad, dimRoundingMode);\n const inputs: DepthwiseConv2dNativeInputs = {x: x4D, filter: $filter};\n const attrs: DepthwiseConv2dNativeAttrs =\n {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n DepthwiseConv2dNative, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const depthwiseConv2d = op({depthwiseConv2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Diag, DiagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Returns a diagonal tensor with given diagonal values.\n *\n * Given a diagonal, this operation returns a tensor with the diagonal and\n * everything else padded with zeros.\n *\n * Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor\n * of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * tf.diag(x).print()\n * ```\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 6, 8], [4, 2])\n *\n * tf.diag(x).print()\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction diag_(x: Tensor): Tensor {\n const $x = convertToTensor(x, 'x', 'diag');\n\n const inputs: DiagInputs = {x: $x};\n\n return ENGINE.runKernel(Diag, inputs as {} as NamedTensorMap);\n}\n\nexport const diag = op({diag_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Dilation2D, Dilation2DAttrs, Dilation2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the grayscale dilation over the input `x`.\n *\n * @param x The input tensor, rank 3 or rank 4 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter tensor, rank 3, of shape\n * `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n * input tensor: `[strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat Specify the data format of the input and output data.\n * Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`\n * is a single number, then `dilationHeight == dilationWidth`. If it is\n * greater than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction dilation2d_(\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 {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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'floorDiv');\n let $b = convertToTensor(b, 'b', 'floorDiv');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: FloorDivInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(FloorDiv, inputs as {} as NamedTensorMap);\n}\n\nexport const floorDiv = op({floorDiv_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RealDiv, RealDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {floorDiv} from './floorDiv';\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction div_(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 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(\n inShape: number[], outShape: number[]): number[] {\n const inRank = inShape.length;\n const dims: number[] = [];\n for (let i = 0; i < inRank; i++) {\n const dim = inRank - 1 - i;\n const a = inShape[dim] || 1;\n const b = outShape[outShape.length - 1 - i] || 1;\n if (b > 1 && a === 1) {\n dims.unshift(dim);\n }\n }\n return dims;\n}\n\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(\n inShape: number[], outShape: number[]): number[] {\n const result: number[] = [];\n for (let i = 0; i < outShape.length; i++) {\n const inDim = inShape[inShape.length - i - 1];\n const outAxis = outShape.length - i - 1;\n const outDim = outShape[outAxis];\n if (inDim == null || (inDim === 1 && outDim > 1)) {\n result.unshift(outAxis);\n }\n }\n return result;\n}\n\nexport function assertAndGetBroadcastShape(\n shapeA: number[], shapeB: number[]): number[] {\n const result: number[] = [];\n const l = Math.max(shapeA.length, shapeB.length);\n\n for (let i = 0; i < l; i++) {\n let a = shapeA[shapeA.length - i - 1];\n if (a == null) {\n a = 1;\n }\n let b = shapeB[shapeB.length - i - 1];\n if (b == null) {\n b = 1;\n }\n if (a === 1) {\n result.unshift(b);\n } else if (b === 1) {\n result.unshift(a);\n } else if (a !== b) {\n const errMsg = `Operands could not be broadcast together with shapes ` +\n `${shapeA} and ${shapeB}.`;\n throw Error(errMsg);\n } else {\n result.unshift(a);\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Equal, EqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a == b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.equal(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction equal_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'equal', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'equal', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: EqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Equal, inputs as {} as NamedTensorMap);\n}\n\nexport const equal = op({equal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Select, SelectInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {broadcastTo} from './broadcast_to';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the elements, either `a` or `b` depending on the `condition`.\n *\n * If the condition is true, select from `a`, otherwise select from `b`.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const a = tf.tensor1d([1 , 2, 3]);\n * const b = tf.tensor1d([-1, -2, -3]);\n *\n * a.where(cond, b).print();\n * ```\n *\n * @param condition The input condition. Must be of dtype bool.\n * @param a If `condition` is rank 1, `a` may have a higher rank but\n * its first dimension must match the size of `condition`.\n * @param b A tensor with the same dtype as `a` and with shape that is\n * compatible with `a`.\n * @return A tensor with same dtype as `a` and `b`, and shape that is\n * broadcastable from `a` and `b`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction where_(\n condition: Tensor|TensorLike, a: T|TensorLike, b: T|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'where');\n const $b = convertToTensor(b, 'b', 'where');\n const $condition = convertToTensor(condition, 'condition', 'where', 'bool');\n // TODO: move this logic to forward function when the broadcastTo op is\n // implemented in WASM.\n // Find the broadcastable shape for $condition, $a, and $b.\n const broadcastShape = assertAndGetBroadcastShape(\n assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);\n const $broadcastedCondition = broadcastTo($condition, broadcastShape);\n const $broadcastedA = broadcastTo($a, broadcastShape);\n const $broadcastedB = broadcastTo($b, broadcastShape);\n\n const inputs: SelectInputs = {\n condition: $broadcastedCondition,\n t: $broadcastedA,\n e: $broadcastedB\n };\n return ENGINE.runKernel(Select, inputs as {} as NamedTensorMap);\n}\n\nexport const where = op({where_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ZerosLike, ZerosLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.zerosLike(x).print();\n * ```\n *\n * @param x The tensor of required shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction zerosLike_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'zerosLike');\n const inputs: ZerosLikeInputs = {x: $x};\n return ENGINE.runKernel(ZerosLike, inputs as {} as NamedTensorMap);\n}\nexport const zerosLike = op({zerosLike_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {div} from './div';\nimport {equal} from './equal';\nimport {op} from './operation';\nimport {where} from './where';\nimport {zerosLike} from './zeros_like';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0\n * if denominator is 0.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n * const c = tf.tensor1d([0, 0, 0, 0]);\n *\n * a.divNoNan(b).print(); // or tf.divNoNan(a, b)\n * a.divNoNan(c).print(); // or tf.divNoNan(a, c)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n * const c = tf.scalar(0);\n *\n * a.divNoNan(b).print(); // or tf.divNoNan(a, b)\n * a.divNoNan(c).print(); // or tf.divNoNan(a, c)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction divNoNan_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n // TODO: Make this into its own kernel.\n let $a = convertToTensor(a, 'a', 'div');\n let $b = convertToTensor(b, 'b', 'div');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const divResult = div($a, $b);\n const zeros = zerosLike(divResult);\n const bEqualsZero = equal($b, zeros);\n return where(bEqualsZero, zeros, divResult) as T;\n}\n\nexport const divNoNan = op({divNoNan_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor,} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the dot product of two matrices and/or vectors, `t1` and `t2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor2d([[1, 2], [3, 4]]);\n * const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n *\n * a.dot(b).print(); // or tf.dot(a, b)\n * b.dot(a).print();\n * b.dot(c).print();\n * ```\n * @param t1 The first tensor in the dot operation.\n * @param t2 The second tensor in the dot operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction dot_(t1: Tensor|TensorLike, t2: Tensor|TensorLike): Tensor {\n const $t1 = convertToTensor(t1, 't1', 'dot');\n const $t2 = convertToTensor(t2, 't2', 'dot');\n\n util.assert(\n ($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2),\n () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +\n `${$t1.rank} and ${$t2.rank}.`);\n\n const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);\n const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);\n\n util.assert(\n t1Inner === t2Inner,\n () => `Error in dot: inner dimensions of inputs must match, but got ` +\n `${t1Inner} and ${t2Inner}.`);\n\n if ($t1.rank === 1 && $t2.rank === 1) {\n const t12D = reshape($t1, [1, -1]);\n const t22D = reshape($t2, [-1, 1]);\n const t1t2 = matMul(t12D, t22D);\n return reshape(t1t2, []);\n } else if ($t1.rank === 1 && $t2.rank === 2) {\n const t12D = reshape($t1, [1, -1]);\n const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n const t1t2 = matMul(t12D, t22D);\n return reshape(t1t2, [t1t2.size]);\n } else if ($t1.rank === 2 && $t2.rank === 1) {\n const t22D = reshape($t2, [-1, 1]);\n const t1t2 = matMul($t1, t22D);\n return reshape(t1t2, [t1t2.size]);\n } else {\n const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n const t1t2 = matMul($t1, t22D);\n return t1t2;\n }\n}\n\nexport const dot = op({dot_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Einsum, EinsumAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Tensor contraction over specified indices and outer product.\n *\n * `einsum` allows defining Tensors by defining their element-wise computation.\n * This computation is based on\n * [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).\n *\n * Some special cases include:\n *\n * Matrix multiplication:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('ij,jk->ik', x, y).print();\n * ```\n *\n * Dot product:\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n * const y = tf.tensor1d([0, 1, 2]);\n * x.print();\n * y.print();\n * tf.einsum('i,i->', x, y).print();\n * ```\n *\n * Batch dot product:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('bi,bi->b', x, y).print();\n * ```\n *\n * Outer prouduct:\n * ```js\n * const x = tf.tensor1d([1, 3, 5]);\n * const y = tf.tensor1d([2, 4, 6]);\n * x.print();\n * y.print();\n * tf.einsum('i,j->ij', x, y).print();\n * ```\n *\n * Matrix transpose:\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * x.print();\n * tf.einsum('ij->ji', x).print();\n * ```\n *\n * Batch matrix transpose:\n * ```js\n * const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);\n * x.print();\n * tf.einsum('bij->bji', x).print();\n * ```\n *\n * Limitations:\n *\n * This implementation of einsum has the following limitations:\n *\n * - Does not support >2 input tensors.\n * - Does not support duplicate axes for any given input tensor. E.g., equation\n * 'ii->' is not supported.\n * - The `...` notation is not supported.\n *\n * @param equation a string describing the contraction, in the same format as\n * [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).\n * @param tensors the input(s) to contract (each one a Tensor), whose shapes\n * should be consistent with equation.\n * @returns The output tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Matrices'}\n */\nexport function einsum_(equation: string, ...tensors: Tensor[]): Tensor {\n const $tensors =\n tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));\n const attrs: EinsumAttrs = {equation};\n return ENGINE.runKernel(\n Einsum, $tensors as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const einsum = op({einsum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Elu, EluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 1, -3, 2]);\n *\n * x.elu().print(); // or tf.elu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction elu_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'elu', 'float32');\n\n const inputs: EluInputs = {x: $x};\n\n return ENGINE.runKernel(Elu, inputs as {} as NamedTensorMap);\n}\n\nexport const elu = op({elu_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Erf, ErfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes Gauss error function of the input `tf.Tensor` element-wise:\n * `erf(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.erf().print(); // or tf.erf(x);\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction erf_(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 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\n/**\n * Returns true if the axis specifies the inner most dimensions of the\n * array.\n */\nexport function axesAreInnerMostDims(axes: number[], rank: number): boolean {\n for (let i = 0; i < axes.length; ++i) {\n if (axes[axes.length - i - 1] !== rank - 1 - i) {\n return false;\n }\n }\n return true;\n}\n\nexport function combineLocations(\n outputLoc: number[], reduceLoc: number[], axes: number[]): number[] {\n const rank = outputLoc.length + reduceLoc.length;\n const loc = [];\n let outIdx = 0;\n let reduceIdx = 0;\n   for (let dim = 0; dim < rank; dim++) {\n if (axes.indexOf(dim) === -1) {\n loc.push(outputLoc[outIdx++]);\n } else {\n loc.push(reduceLoc[reduceIdx++]);\n }\n }\n return loc;\n}\n\nexport function computeOutAndReduceShapes(\n aShape: number[], axes: number[]): [number[], number[]] {\n const outShape = [];\n const rank = aShape.length;\n for (let dim = 0; dim < rank; dim++) {\n if (axes.indexOf(dim) === -1) {\n outShape.push(aShape[dim]);\n }\n }\n const reduceShape = axes.map(dim => aShape[dim]);\n return [outShape, reduceShape];\n}\n\nexport function expandShapeToKeepDim(\n shape: number[], axes: number[]): number[] {\n const reduceSubShape = axes.map(x => 1);\n return combineLocations(shape, reduceSubShape, axes);\n}\n\nexport function assertAxesAreInnerMostDims(\n msg: string, axes: number[], rank: number): void {\n util.assert(\n axesAreInnerMostDims(axes, rank),\n () => `${msg} supports only inner-most axes for now. ` +\n `Got axes ${axes} and rank-${rank} input.`);\n}\n\n/**\n * Returns the axes permutation to be used with `tf.transpose`, if such\n * permutation is necessary. Otherwise it returns null. This method is used by\n * operations that operate only on inner-most axes.\n */\nexport function getAxesPermutation(axes: number[], rank: number): number[]|\n null {\n if (axesAreInnerMostDims(axes, rank)) {\n return null;\n }\n const result: number[] = [];\n for (let i = 0; i < rank; ++i) {\n if (axes.indexOf(i) === -1) {\n result.push(i);\n }\n }\n axes.forEach(axis => result.push(axis));\n return result;\n}\n\n/** Returns the axes permutation that undoes the original permutation. */\nexport function getUndoAxesPermutation(axes: number[]): number[] {\n return axes.map((axis, i) => [i, axis])\n .sort((a, b) => a[1] - b[1])\n .map(x => x[0]);\n}\n\nexport function getInnerMostAxes(numAxes: number, rank: number): number[] {\n const res: number[] = [];\n for (let i = rank - numAxes; i < rank; ++i) {\n res.push(i);\n }\n return res;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Max, MaxAttrs, MaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the maximum of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.max().print(); // or tf.max(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.max(axis).print(); // or tf.max(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction max_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'max');\n\n const inputs: MaxInputs = {x: $x};\n const attrs: MaxAttrs = {reductionIndices: axis, keepDims};\n\n return ENGINE.runKernel(\n Max, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const max = op({max_});\n","/**\n * @license\n * Copyright 2020 Google 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_(\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 */\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_(\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 {Scalar} from '../tensor';\nimport {DataType} from '../types';\nimport {isTypedArray} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.scalar` as it makes the code more readable.\n *\n * ```js\n * tf.scalar(3.14).print();\n * ```\n *\n * @param value The value of the scalar.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function scalar(\n value: number|boolean|string|Uint8Array, dtype?: DataType): Scalar {\n if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&\n dtype !== 'complex64') {\n throw new Error(\n 'Error creating a new Scalar: value must be a primitive ' +\n '(number|boolean|string)');\n }\n if (dtype === 'string' && isTypedArray(value) &&\n !(value instanceof Uint8Array)) {\n throw new Error(\n 'When making a scalar from encoded string, ' +\n 'the value must be `Uint8Array`.');\n }\n const shape: number[] = [];\n const inferredShape: number[] = [];\n return makeTensor(value, shape, inferredShape, dtype) as Scalar;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sqrt, SqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.sqrt().print(); // or tf.sqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sqrt_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sqrt', 'float32');\n\n const inputs: SqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Sqrt, inputs as {} as NamedTensorMap);\n}\nexport const sqrt = op({sqrt_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Computes square of `x` element-wise: `x ^ 2`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);\n *\n * x.square().print(); // or tf.square(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction square_(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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(\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 {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {abs} from './abs';\nimport * as axis_util from './axis_util';\nimport {max} from './max';\nimport {min} from './min';\nimport {op} from './operation';\nimport {pow} from './pow';\nimport {reshape} from './reshape';\nimport {scalar} from './scalar';\nimport {sqrt} from './sqrt';\nimport {square} from './square';\nimport {sum} from './sum';\n\n/**\n * Computes the norm of scalar, vectors, and matrices.\n * This function can compute several different vector norms (the 1-norm, the\n * Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)\n * and matrix norms (Frobenius, 1-norm, and inf-norm).\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.norm().print(); // or tf.norm(x)\n * ```\n *\n * @param x The input array.\n * @param ord Optional. Order of the norm. Supported norm types are\n * following:\n *\n * | ord | norm for matrices | norm for vectors\n * |------------|---------------------------|---------------------\n * |'euclidean' |Frobenius norm |2-norm\n * |'fro' |Frobenius norm\t |\n * |Infinity |max(sum(abs(x), axis=1)) |max(abs(x))\n * |-Infinity |min(sum(abs(x), axis=1)) |min(abs(x))\n * |1 |max(sum(abs(x), axis=0)) |sum(abs(x))\n * |2 | |sum(abs(x)^2)^(1/2)\n *\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. norm(x, ord) is equivalent\n * to norm(x.reshape([-1]), ord). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction norm_(\n x: Tensor|TensorLike, ord: number|'euclidean'|'fro' = 'euclidean',\n axis: number|number[] = null, keepDims = false): Tensor {\n x = convertToTensor(x, 'x', 'norm');\n\n const norm = normImpl(x, ord, axis);\n let keepDimsShape = norm.shape;\n if (keepDims) {\n const axes = parseAxisParam(axis, x.shape);\n keepDimsShape = axis_util.expandShapeToKeepDim(norm.shape, axes);\n }\n return reshape(norm, keepDimsShape);\n}\n\nfunction normImpl(\n x: Tensor, p: number|string, axis: number|number[] = null): Tensor {\n if (x.rank === 0) {\n return abs(x);\n }\n\n // consider vector when no axis is specified\n if (x.rank !== 1 && axis === null) {\n return normImpl(reshape(x, [-1]), p, axis);\n }\n\n // vector\n if (x.rank === 1 || typeof axis === 'number' ||\n Array.isArray(axis) && axis.length === 1) {\n if (p === 1) {\n return sum(abs(x), axis);\n }\n if (p === Infinity) {\n return max(abs(x), axis);\n }\n if (p === -Infinity) {\n return min(abs(x), axis);\n }\n if (p === 'euclidean' || p === 2) {\n // norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2\n return sqrt(sum(pow(abs(x), scalar(2, 'int32')), axis));\n }\n\n throw new Error(`Error in norm: invalid ord value: ${p}`);\n }\n\n // matrix (assumption axis[0] < axis[1])\n if (Array.isArray(axis) && axis.length === 2) {\n if (p === 1) {\n return max(sum(abs(x), axis[0]), axis[1] - 1);\n }\n if (p === Infinity) {\n return max(sum(abs(x), axis[1]), axis[0]);\n }\n if (p === -Infinity) {\n return min(sum(abs(x), axis[1]), axis[0]);\n }\n if (p === 'fro' || p === 'euclidean') {\n // norm(x) = sqrt(sum(pow(x, 2)))\n return sqrt(sum(square(x), axis));\n }\n\n throw new Error(`Error in norm: invalid ord value: ${p}`);\n }\n\n throw new Error(`Error in norm: invalid axis: ${axis}`);\n}\n\nexport const norm = op({norm_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {norm} from './norm';\nimport {op} from './operation';\n\n/**\n * Computes the Euclidean norm of scalar, vectors, and matrices.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.euclideanNorm().print(); // or tf.euclideanNorm(x)\n * ```\n *\n * @param x The input array.\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. euclideanNorm(x) is equivalent\n * to euclideanNorm(x.reshape([-1])). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction euclideanNorm_(\n x: Tensor|TensorLike, axis: number|number[] = null,\n keepDims = false): Tensor {\n return norm(x, 'euclidean', axis, keepDims);\n}\n\nexport const euclideanNorm = op({euclideanNorm_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Exp, ExpInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.exp().print(); // or tf.exp(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction exp_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'exp');\n\n const inputs: ExpInputs = {x: $x};\n return ENGINE.runKernel(Exp, inputs as {} as NamedTensorMap);\n}\nexport const exp = op({exp_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Returns a `tf.Tensor` that has expanded rank, by inserting a dimension\n * into the tensor's shape.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const axis = 1;\n * x.expandDims(axis).print();\n * ```\n *\n * @param x The input tensor whose dimensions are to be expanded.\n * @param axis The dimension index at which to insert shape of `1`. Defaults\n * to 0 (the first dimension).\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction expandDims_(x: Tensor|TensorLike, axis = 0): T {\n const $x = convertToTensor(x, 'x', 'expandDims', 'string_or_numeric');\n\n util.assert(axis <= $x.rank, () => 'Axis must be <= rank of the tensor');\n\n const inputs: ExpandDimsInputs = {input: $x};\n const attrs: ExpandDimsAttrs = {dim: axis};\n\n return ENGINE.runKernel(\n ExpandDims, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const expandDims = op({expandDims_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Expm1, Expm1Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` minus one element-wise.\n * `e ^ x - 1`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.expm1().print(); // or tf.expm1(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction expm1_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'expm1');\n\n const inputs: Expm1Inputs = {x: $x};\n return ENGINE.runKernel(Expm1, inputs as {} as NamedTensorMap);\n}\nexport const expm1 = op({expm1_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Construct a tensor by repeating it the number of times given by reps.\n *\n * This operation creates a new tensor by replicating `input` `reps`\n * times. The output tensor's `i`th dimension has `input.shape[i] *\n * reps[i]` elements, and the values of `input` are replicated\n * `reps[i]` times along the `i`th dimension. For example, tiling\n * `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n *\n * a.tile([2]).print(); // or a.tile([2])\n * ```\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.tile([1, 2]).print(); // or a.tile([1, 2])\n * ```\n * @param x The tensor to tile.\n * @param reps Determines the number of replications per dimension.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction tile_(x: T|TensorLike, reps: number[]): T {\n const $x = convertToTensor(x, 'x', 'tile', 'string_or_numeric');\n util.assert(\n $x.rank === reps.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of reps ${reps}.`);\n\n const inputs: TileInputs = {x: $x};\n const attrs: TileAttrs = {reps};\n\n return ENGINE.runKernel(\n Tile, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const tile = op({tile_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {DataType} from '../types';\n\nimport {buffer} from './buffer';\nimport {expandDims} from './expand_dims';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {tile} from './tile';\n\n/**\n * Create an identity matrix.\n *\n * @param numRows Number of rows.\n * @param numColumns Number of columns. Defaults to `numRows`.\n * @param batchShape If provided, will add the batch shape to the beginning\n * of the shape of the returned `tf.Tensor` by repeating the identity\n * matrix.\n * @param dtype Data type.\n * @returns Identity matrix of the specified size and data type, possibly\n * with batch repetition if `batchShape` is specified.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction eye_(\n numRows: number, numColumns?: number,\n batchShape?:\n [\n number\n ]|[number,\n number]|[number, number, number]|[number, number, number, number],\n dtype: DataType = 'float32'): Tensor2D {\n if (numColumns == null) {\n numColumns = numRows;\n }\n const buff = buffer([numRows, numColumns], dtype);\n const n = numRows <= numColumns ? numRows : numColumns;\n for (let i = 0; i < n; ++i) {\n buff.set(1, i, i);\n }\n const out: Tensor2D = reshape(buff.toTensor(), [numRows, numColumns]);\n if (batchShape == null) {\n return out;\n } else {\n if (batchShape.length === 1) {\n return tile(expandDims(out, 0), [batchShape[0], 1, 1]) as Tensor2D;\n } else if (batchShape.length === 2) {\n // tslint:disable-next-line:no-unnecessary-type-assertion\n return tile(\n expandDims(expandDims(out, 0), 0),\n [batchShape[0], batchShape[1], 1, 1]) as Tensor2D;\n } else if (batchShape.length === 3) {\n // tslint:disable-next-line:no-unnecessary-type-assertion\n return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [\n batchShape[0], batchShape[1], batchShape[2], 1, 1\n ]) as Tensor2D;\n } else {\n throw new Error(\n `eye() currently supports only 1D and 2D ` +\n // tslint:disable-next-line:no-any\n `batchShapes, but received ${(batchShape as any).length}D.`);\n }\n }\n}\n\nexport const eye = op({eye_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'floor', 'float32');\n\n const inputs: FloorInputs = {x: $x};\n return ENGINE.runKernel(Floor, inputs as {} as NamedTensorMap);\n}\nexport const floor = op({floor_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {GatherV2, GatherV2Attrs, GatherV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Gather slices from tensor `x`'s axis `axis` according to `indices`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const indices = tf.tensor1d([1, 3, 3], 'int32');\n *\n * x.gather(indices).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const indices = tf.tensor1d([1, 1, 0], 'int32');\n *\n * x.gather(indices).print();\n * ```\n * @param x The input tensor whose slices are to be gathered.\n * @param indices The indices of the values to extract.\n * @param axis The axis over which to select values. Defaults to 0.\n * @param batchDims Optional. The number of batch dimensions. It must be less\n * than or equal to rank(indices). Defaults to 0.\n * The output tensor will have shape of\n * `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction gather_(\n x: T|TensorLike, indices: Tensor|TensorLike, axis = 0, batchDims = 0): T {\n const $x = convertToTensor(x, 'x', 'gather');\n const $indices = convertToTensor(indices, 'indices', 'gather', 'int32');\n\n const inputs: GatherV2Inputs = {x: $x, indices: $indices};\n const attrs: GatherV2Attrs = {axis, batchDims};\n\n return ENGINE.runKernel(\n GatherV2, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const gather = op({gather_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Greater, GreaterInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a > b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greater(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greater_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'greater', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'greater', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: GreaterInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Greater, inputs as {} as NamedTensorMap);\n}\n\nexport const greater = op({greater_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {GreaterEqual, GreaterEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a >= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greaterEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greaterEqual_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'greaterEqual', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'greaterEqual', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: GreaterEqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(GreaterEqual, inputs as {} as NamedTensorMap);\n}\n\nexport const greaterEqual = op({greaterEqual_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Imag, ImagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n/**\n * Returns the imaginary part of a complex (or real) tensor.\n *\n * Given a tensor input, this operation returns a tensor of type float that is\n * the imaginary part of each element in input considered as a complex number.\n * If input is real, a tensor of all zeros is returned.\n *\n * ```js\n * const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);\n * tf.imag(x).print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction imag_(input: T|TensorLike): T {\n const $input = convertToTensor(input, 'input', 'imag');\n\n const inputs: ImagInputs = {input: $input};\n return ENGINE.runKernel(Imag, inputs as {} as NamedTensorMap);\n}\n\nexport const imag = op({imag_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsFinite, IsFiniteInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are finite.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isFinite().print(); // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isFinite_(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_(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 * Returns which elements of x are NaN.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isNaN().print(); // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isNaN_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'isNaN');\n const inputs: IsNanInputs = {x: $x};\n\n return ENGINE.runKernel(IsNan, inputs as {} as NamedTensorMap);\n}\nexport const isNaN = op({isNaN_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LeakyRelu, LeakyReluAttrs, LeakyReluInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise.\n *\n * See\n * [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](\n * http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.leakyRelu(0.1).print(); // or tf.leakyRelu(x, 0.1)\n * ```\n * @param x The input tensor.\n * @param alpha The scaling factor for negative values, defaults to 0.2.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction leakyRelu_(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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'less', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'less', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LessInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Less, inputs as {} as NamedTensorMap);\n}\n\nexport const less = op({less_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LessEqual, LessEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a <= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.lessEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction lessEqual_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'lessEqual', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'lessEqual', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LessEqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(LessEqual, inputs as {} as NamedTensorMap);\n}\n\nexport const lessEqual = op({lessEqual_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LinSpace, LinSpaceAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Return an evenly spaced sequence of numbers over the given interval.\n *\n * ```js\n * tf.linspace(0, 9, 10).print();\n * ```\n * @param start The start value of the sequence.\n * @param stop The end value of the sequence.\n * @param num The number of values to generate.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function linspace(start: number, stop: number, num: number): Tensor1D {\n if (num <= 0) {\n throw new Error('The number of values should be positive.');\n }\n\n const attrs: LinSpaceAttrs = {start, stop, num};\n return ENGINE.runKernel(LinSpace, {}, attrs as {} as NamedAttrMap);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LRN, LRNAttrs, LRNInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Normalizes the activation of a local neighborhood across or within\n * channels.\n *\n * @param x The input tensor. The 4-D input tensor is treated as a 3-D array\n * of 1D vectors (along the last dimension), and each vector is\n * normalized independently.\n * @param depthRadius The number of adjacent channels in the 1D normalization\n * window.\n * @param bias A constant bias term for the basis.\n * @param alpha A scale factor, usually positive.\n * @param beta An exponent.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction localResponseNormalization_(\n x: T|TensorLike, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5): T {\n const $x = convertToTensor(x, 'x', 'localResponseNormalization');\n util.assert(\n $x.rank === 4 || $x.rank === 3,\n () => `Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${$x.rank}.`);\n util.assert(\n util.isInt(depthRadius),\n () => `Error in localResponseNormalization: depthRadius must be an ` +\n `integer but got depthRadius ${depthRadius}.`);\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n const inputs: LRNInputs = {x: x4D};\n\n const attrs: LRNAttrs = {depthRadius, bias, alpha, beta};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n LRN, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n } else {\n return res;\n }\n}\n\nexport const localResponseNormalization = op({localResponseNormalization_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log, LogInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E]);\n *\n * x.log().print(); // or tf.log(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'log', 'float32');\n\n const inputs: LogInputs = {x: $x};\n return ENGINE.runKernel(Log, inputs as {} as NamedTensorMap);\n}\nexport const log = op({log_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log1p, Log1pInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` plus one\n * element-wise: `ln(1 + x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E - 1]);\n *\n * x.log1p().print(); // or tf.log1p(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log1p_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'log1p');\n\n const inputs: Log1pInputs = {x: $x};\n return ENGINE.runKernel(Log1p, inputs as {} as NamedTensorMap);\n}\nexport const log1p = op({log1p_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CustomGradientFunc, ENGINE} from './engine';\nimport {Scalar, Tensor, Variable} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {convertToTensor, convertToTensorArray} from './tensor_util_env';\nimport {TensorLike} from './types';\nimport * as util from './util';\n\n/**\n * Provided `f(x)`, returns another function `g(x, dy?)`, which gives the\n * gradient of `f(x)` with respect to `x`.\n *\n * If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to\n * `x` is computed instead. `f(x)` must take a single tensor `x` and return a\n * single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.grad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * g(x).print();\n * ```\n *\n * ```js\n * // f(x) = x ^ 3\n * const f = x => x.pow(tf.scalar(3, 'int32'));\n * // f'(x) = 3x ^ 2\n * const g = tf.grad(f);\n * // f''(x) = 6x\n * const gg = tf.grad(g);\n *\n * const x = tf.tensor1d([2, 3]);\n * gg(x).print();\n * ```\n *\n * @param f The function f(x), to compute gradient for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grad(f: (x: Tensor) => Tensor): (\n x: TensorLike|Tensor, dy?: TensorLike|Tensor) => Tensor {\n util.assert(\n util.isFunction(f), () => 'The f passed in grad(f) must be a function');\n return (x: TensorLike|Tensor, dy?: TensorLike|Tensor): Tensor => {\n // x can be of any dtype, thus null as the last argument.\n const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');\n const $dy: Tensor =\n (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;\n return ENGINE.tidy(() => {\n const {value, grads} = ENGINE.gradients(() => f($x), [$x], $dy);\n if ($dy != null) {\n util.assertShapesMatch(\n value.shape, $dy.shape,\n 'The shape of dy passed in grad(f)(x, dy) must match the shape ' +\n 'returned by f(x)');\n }\n checkGrads(grads);\n return grads[0];\n });\n };\n}\n\n/**\n * Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,\n * which gives an array of gradients of `f()` with respect to each input\n * [`x1`,`x2`,...].\n *\n * If `dy` is passed when calling `g()`, the gradient of\n * `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.\n * The provided `f` must take one or more tensors and return a single tensor\n * `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df / da = b, df / db = a\n * const g = tf.grads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const [da, db] = g([a, b]);\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @param f The function `f(x1, x2,...)` to compute gradients for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grads(f: (...args: Tensor[]) => Tensor): (\n args: Array, 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, 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(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(f: (...args: Tensor[]) => O): (\n args: Tensor[], dy?: O) => {\n grads: Tensor[];\n value: O;\n} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in valueAndGrads(f) must be a function');\n return (args: Tensor[], dy?: O) => {\n util.assert(\n Array.isArray(args) && args.every(arg => arg instanceof Tensor),\n () => 'The args passed in valueAndGrads(f)(args) must be array of ' +\n 'tensors');\n util.assert(\n dy == null || dy instanceof Tensor,\n () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');\n const res = ENGINE.gradients(() => f(...args), args, dy);\n if (dy != null) {\n util.assertShapesMatch(\n res.value.shape, dy.shape,\n 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +\n 'match the shape returned by f([x1,...])');\n }\n checkGrads(res.grads);\n return res;\n };\n}\n\n/**\n * Computes and returns the gradient of f(x) with respect to the list of\n * trainable variables provided by `varList`. If no list is provided, it\n * defaults to all trainable variables.\n *\n * ```js\n * const a = tf.variable(tf.tensor1d([3, 4]));\n * const b = tf.variable(tf.tensor1d([5, 6]));\n * const x = tf.tensor1d([1, 2]);\n *\n * // f(a, b) = a * x ^ 2 + b * x\n * const f = () => a.mul(x.square()).add(b.mul(x)).sum();\n * // df/da = x ^ 2, df/db = x\n * const {value, grads} = tf.variableGrads(f);\n *\n * Object.keys(grads).forEach(varName => grads[varName].print());\n * ```\n *\n * @param f The function to execute. f() should return a scalar.\n * @param varList The list of variables to compute the gradients with respect\n * to. Defaults to all trainable variables.\n * @returns An object with the following keys and values:\n * - `value`: The value of the function `f`.\n * - `grads`: A map from the names of the variables to the gradients.\n * If the `varList` argument is provided explicitly and contains a subset of\n * non-trainable variables, this map in the return value will contain keys\n * that map the names of the non-trainable variables to `null`.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction variableGrads(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in variableGrads(f) must be a function');\n util.assert(\n varList == null ||\n Array.isArray(varList) && varList.every(v => v instanceof Variable),\n () =>\n 'The varList passed in variableGrads(f, varList) must be an array ' +\n 'of variables');\n\n const specifiedVarList = varList != null;\n if (!specifiedVarList) {\n // Get all of the trainable variables.\n varList = [];\n for (const varName in ENGINE.registeredVariables) {\n varList.push(ENGINE.registeredVariables[varName]);\n }\n }\n\n const specifiedNonTrainable: Variable[] =\n specifiedVarList ? varList.filter(variable => !variable.trainable) : null;\n\n // Prune non-trainable variables.\n const originalVarCount = varList.length;\n varList = varList.filter(variable => variable.trainable);\n util.assert(\n varList.length > 0,\n () => `variableGrads() expects at least one of the input variables to ` +\n `be trainable, but none of the ${originalVarCount} variables is ` +\n `trainable.`);\n\n const allowNoGradients = true;\n const {value, grads} = ENGINE.gradients(f, varList, null, allowNoGradients);\n\n util.assert(\n grads.some(g => g != null),\n () => 'Cannot find a connection between any variable and the result of ' +\n 'the loss function y=f(x). Please make sure the operations that ' +\n 'use variables are inside the function f passed to minimize().');\n util.assert(\n value.rank === 0,\n () => `The f passed in variableGrads(f) must return a scalar, but it ` +\n `returned a rank-${value.rank} tensor`);\n\n const namedGrads: NamedTensorMap = {};\n varList.forEach((v, i) => {\n if (grads[i] != null) {\n namedGrads[v.name] = grads[i];\n }\n });\n if (specifiedNonTrainable != null) {\n // If varList is explicitly provided and contains non-trainable values,\n // add them to the returned gradients with `null` values.\n specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);\n }\n return {value, grads: namedGrads};\n}\n\n/**\n * Overrides the gradient computation of a function `f`.\n *\n * Takes a function\n * `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`\n * and returns another function `g(...inputs)` which takes the same inputs as\n * `f`. When called, `g` returns `f().value`. In backward mode, custom gradients\n * with respect to each input of `f` are computed using `f().gradFunc`.\n *\n * The `save` function passed to `f` should be used for saving tensors needed\n * in the gradient. And the `saved` passed to the `gradFunc` is a\n * `NamedTensorMap`, which contains those saved tensors.\n *\n * ```js\n * const customOp = tf.customGrad((x, save) => {\n * // Save x to make sure it's available later for the gradient.\n * save([x]);\n * // Override gradient of our custom x ^ 2 op to be dy * abs(x);\n * return {\n * value: x.square(),\n * // Note `saved.x` which points to the `x` we saved earlier.\n * gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]\n * };\n * });\n *\n * const x = tf.tensor1d([-1, -2, 3]);\n * const dx = tf.grad(x => customOp(x));\n *\n * console.log(`f(x):`);\n * customOp(x).print();\n * console.log(`f'(x):`);\n * dx(x).print();\n * ```\n *\n * @param f The function to evaluate in forward mode, which should return\n * `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`\n * returns the custom gradients of `f` with respect to its inputs.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction customGrad(f: CustomGradientFunc):\n (...args: Tensor[]) => T {\n return ENGINE.customGrad(f);\n}\n\nfunction checkGrads(grads: Tensor[]) {\n const numNullGradients = grads.filter(g => g == null).length;\n if (numNullGradients > 0) {\n throw new Error(\n `Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.`);\n }\n}\n\nexport {\n customGrad,\n variableGrads,\n valueAndGrad,\n valueAndGrads,\n grad,\n grads,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Neg, NegInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes `-1 * x` element-wise.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, -2, 0], [2, 2]);\n *\n * x.neg().print(); // or tf.neg(x)\n * ```\n *\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction neg_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'neg');\n\n const inputs: NegInputs = {x: $x};\n return ENGINE.runKernel(Neg, inputs as {} as NamedTensorMap);\n}\nexport const neg = op({neg_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softplus, SoftplusInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.softplus().print(); // or tf.softplus(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction softplus_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'softplus');\n\n const inputs: SoftplusInputs = {x: $x};\n return ENGINE.runKernel(Softplus, inputs as {} as NamedTensorMap);\n}\nexport const softplus = op({softplus_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {customGrad} from '../gradients';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {mul} from './mul';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {softplus} from './softplus';\n\n/**\n * Computes log sigmoid of the input `tf.Tensor` element-wise:\n * `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.logSigmoid().print(); // or tf.logSigmoid(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction logSigmoid_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'logSigmoid');\n\n // Use a custom gradient to maintain previous implementation.\n // There is no LogSigmoid kernel in TF so we can't use engine.runKernel\n // directly\n const customOp = customGrad((x: Tensor) => {\n // TODO(yassogba) we can remove the chained softplus call here only\n // after backends have modualrized softplus at which point we can call\n // engine runKernel(..., Sotfplus, ...) directly.\n const value = neg(softplus(neg(x)));\n\n const gradFunc = (dy: T) => {\n const derX = mul(dy, sigmoid(neg(x)));\n return derX;\n };\n return {value, gradFunc};\n });\n\n return customOp($x) as T;\n}\nexport const logSigmoid = op({logSigmoid_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'sub');\n let $b = convertToTensor(b, 'b', 'sub');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: SubInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Sub, inputs as {} as NamedTensorMap);\n}\n\nexport const sub = op({sub_});\n","/**\n * @license\n * Copyright 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_(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 = (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 {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_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'logSumExp');\n\n const axes = parseAxisParam(axis, $x.shape);\n const xMax = max($x, axes, true /* keepDims */);\n const a = sub($x, xMax);\n const b = exp(a);\n const c = sum(b, axes);\n const d = log(c);\n const res = add(reshape(xMax, d.shape), d);\n\n if (keepDims) {\n const newShape = expandShapeToKeepDim(res.shape, axes);\n return reshape(res, newShape) as T;\n }\n return res as T;\n}\n\nexport const logSumExp = op({logSumExp_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LogicalAnd, LogicalAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a AND b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalAnd(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalAnd_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'logicalAnd', 'bool');\n const $b = convertToTensor(b, 'b', 'logicalAnd', 'bool');\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LogicalAndInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(LogicalAnd, inputs as {} as NamedTensorMap);\n}\n\nexport const logicalAnd = op({logicalAnd_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalNot, LogicalNotInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `NOT x` element-wise.\n *\n * ```js\n * const a = tf.tensor1d([false, true], 'bool');\n *\n * a.logicalNot().print();\n * ```\n *\n * @param x The input tensor. Must be of dtype 'bool'.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalNot_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'logicalNot', 'bool');\n const inputs: LogicalNotInputs = {x: $x};\n return ENGINE.runKernel(LogicalNot, inputs as {} as NamedTensorMap);\n}\n\nexport const logicalNot = op({logicalNot_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalOr, LogicalOrInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a OR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalOr(b).print();\n * ```\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalOr_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'logicalOr', 'bool');\n const $b = convertToTensor(b, 'b', 'logicalOr', 'bool');\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LogicalOrInputs = {a: $a, b: $b};\n return ENGINE.runKernel(LogicalOr, inputs as {} as NamedTensorMap);\n}\nexport const logicalOr = op({logicalOr_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {logicalAnd} from './logical_and';\nimport {logicalNot} from './logical_not';\nimport {logicalOr} from './logical_or';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a XOR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalXor(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalXor_(\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 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SearchSorted, SearchSortedAttrs, SearchSortedInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nconst INT32_MAX = 2147483648;\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The side argument controls which index is returned if a value lands exactly\n * on an edge.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'sortedSequence' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.searchSorted(edges, values, 'left');\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.searchSorted(seq, values, 'left');\n * result2.print(); // [0, 2, 3]\n * const result3 = tf.searchSorted(seq, values, 'right');\n * result3.print(); // [1, 2, 5]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n * [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n * [0.1, 6.6, 4.5, ]]);\n * const result4 = tf.searchSorted(sortedSequence, values, 'left');\n * result4.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @param side: 'left'|'right'. Defaults to 'left'. 'left' corresponds to lower\n * bound and 'right' to upper bound.\n * @return An N-D int32 tensor the size of values containing the result of\n * applying either lower bound or upper bound (depending on side) to each\n * value. The result is not a global index to the entire Tensor, but the\n * index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction searchSorted_(\n sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike,\n side: 'left'|'right' = 'left'): Tensor {\n const $sortedSequence =\n convertToTensor(sortedSequence, 'sortedSequence', 'searchSorted');\n const $values = convertToTensor(values, 'values', 'searchSorted');\n\n const sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];\n const valuesSize = $values.shape[$values.shape.length - 1];\n const $sortedSequence2D = reshape($sortedSequence, [-1, sequenceSize]);\n const $values2D = reshape($values, [-1, valuesSize]);\n\n if ($sortedSequence2D.rank < 2) {\n throw new Error(`Sorted input argument must be at least 2-dimensional`);\n }\n if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) {\n throw new Error(\n `Leading dimension of 'sortedSequence' and 'values' must match.`);\n }\n if (sizeFromShape($values2D.shape) >= INT32_MAX) {\n throw new Error(`values tensor size must less than ${INT32_MAX}`);\n }\n if ($sortedSequence2D.shape[1] >= INT32_MAX) {\n throw new Error(`trailing dim_size must less than ${\n INT32_MAX} for int32 output type, was ${$sortedSequence2D.shape[1]}`);\n }\n\n const inputs: SearchSortedInputs = {\n sortedSequence: $sortedSequence2D,\n values: $values2D,\n };\n const attrs: SearchSortedAttrs = {side};\n\n return ENGINE.runKernel(SearchSorted, inputs as {}, attrs as {});\n}\n\nexport const searchSorted = op({searchSorted_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than or equal to the\n * value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'lowerBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.lowerBound(edges, values);\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.lowerBound(seq, values);\n * result2.print(); // [0, 2, 3]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n * [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n * [0.1, 6.6, 4.5, ]]);\n * const result3 = tf.lowerBound(sortedSequence, values);\n * result3.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n * applying lower bound to each value. The result is not a global index to\n * the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function lowerBound(\n sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n return searchSorted(sortedSequence, values, 'left');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool, MaxPoolAttrs, MaxPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D max pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction maxPool_(\n x: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'maxPool');\n const dilations = 1;\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n conv_util.checkPadOnDimRoundingMode('maxPool', pad, dimRoundingMode);\n const inputs: MaxPoolInputs = {x: x4D};\n const attrs: MaxPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n MaxPool, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const maxPool = op({maxPool_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D max pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.maxPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n * `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n * `[filterDepth, filterHeight, filterWidth]`.\n * If `filterSize` is a single number,\n * then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n * `[strideDepth, strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n * \"NDHWC\". Specify the data format of the input and output data. With the\n * default format \"NDHWC\", the data is stored in the order of: [batch,\n * depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPool3d_(\n x: T|TensorLike, filterSize: [number, number, number]|number = [1, 1, 1],\n strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n const $x = convertToTensor(x, 'x', 'maxPool3d');\n\n let x5D = $x as Tensor5D;\n let reshapedTo5D = false;\n if ($x.rank === 4) {\n reshapedTo5D = true;\n x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n }\n\n util.assert(\n x5D.rank === 5,\n () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n util.assert(\n dataFormat === 'NDHWC',\n () => `Error in maxPool3d: Only NDHWC is currently supported, ` +\n `but got dataFormat of ${dataFormat}`);\n checkPadOnDimRoundingMode('maxPool3d', pad, dimRoundingMode);\n const inputs: MaxPool3DInputs = {x: x5D};\n const attrs:\n MaxPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n MaxPool3D, inputs as {} 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_(\n x: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number, pad: 'valid'|'same'|number,\n includeBatchInIndex = false): NamedTensorMap {\n const $x = convertToTensor(x, 'x', 'maxPoolWithArgmax');\n\n const inputs: MaxPoolWithArgmaxInputs = {x: $x};\n const attrs:\n MaxPoolWithArgmaxAttrs = {filterSize, strides, pad, includeBatchInIndex};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const result = ENGINE.runKernel(\n MaxPoolWithArgmax, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor[];\n\n return {result: result[0], indexes: result[1]};\n}\n\nexport const maxPoolWithArgmax = op({maxPoolWithArgmax_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Maximum, MaximumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the max of a and b (`a > b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `tf.maximumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.maximum(b).print(); // or tf.maximum(a, b)\n * ```\n *\n * ```js\n * // Broadcast maximum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.maximum(b).print(); // or tf.maximum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction maximum_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'maximum');\n let $b = convertToTensor(b, 'b', 'maximum');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'bool') {\n $a = cast($a, 'int32');\n $b = cast($b, 'int32');\n }\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: MaximumInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Maximum, inputs as {} as NamedTensorMap);\n}\n\nexport const maximum = op({maximum_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Mean, MeanAttrs, MeanInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the mean of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is\n * true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with\n * a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.mean().print(); // or tf.mean(a)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.mean(axis).print(); // or tf.mean(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction mean_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'mean');\n\n const inputs: MeanInputs = {x: $x};\n const attrs: MeanAttrs = {axis, keepDims};\n\n return ENGINE.runKernel(\n Mean, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const mean = op({mean_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {makeZerosTypedArray, sizeFromShape} from '../util';\n\nimport {complex} from './complex';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0.\n *\n * ```js\n * tf.zeros([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Can\n * be 'float32', 'int32' or 'bool'. Defaults to 'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function zeros(\n shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor {\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;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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(\n shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor {\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;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {matMul} from './mat_mul';\nimport {ones} from './ones';\nimport {reshape} from './reshape';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\n\n/**\n * Broadcasts parameters for evaluation on an N-D grid.\n *\n * Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n * of N-D coordinate arrays for evaluating expressions on an N-D grid.\n *\n * Notes:\n * `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n * When the `indexing` argument is set to 'xy' (the default), the broadcasting\n * instructions for the first two dimensions are swapped.\n * Examples:\n * Calling `const [X, Y] = meshgrid(x, y)` with the tensors\n *\n * ```javascript\n * const x = [1, 2, 3];\n * const y = [4, 5, 6];\n * const [X, Y] = tf.meshgrid(x, y);\n * // X = [[1, 2, 3],\n * // [1, 2, 3],\n * // [1, 2, 3]]\n * // Y = [[4, 4, 4],\n * // [5, 5, 5],\n * // [6, 6, 6]]\n * ```\n *\n * @param x Tensor with rank geq 1.\n * @param y Tensor with rank geq 1.\n * @param indexing\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nexport function meshgrid(\n x?: T|TensorLike, y?: T|TensorLike, {indexing = 'xy'} = {}): T[] {\n if (indexing !== 'xy' && indexing !== 'ij') {\n throw new TypeError(\n `${indexing} is not a valid third argument to meshgrid`);\n }\n if (x === undefined) {\n return [];\n }\n let $x = convertToTensor(\n x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');\n\n if (y === undefined) {\n return [$x];\n }\n let $y = convertToTensor(\n y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');\n\n const w = sizeFromShape($x.shape);\n const h = sizeFromShape($y.shape);\n\n if (indexing === 'xy') {\n $x = reshape($x, [1, -1]) as T;\n $y = reshape($y, [-1, 1]) as T;\n return [\n matMul(ones([h, 1], $x.dtype), $x),\n matMul($y, ones([1, w], $y.dtype)),\n ];\n }\n\n $x = reshape($x, [-1, 1]) as T;\n $y = reshape($y, [1, -1]) as T;\n return [\n matMul($x, ones([1, h], $x.dtype)),\n matMul(ones([w, 1], $y.dtype), $y),\n ];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Minimum, MinimumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the min of a and b (`a < b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `minimumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.minimum(b).print(); // or tf.minimum(a, b)\n * ```\n *\n * ```js\n * // Broadcast minimum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.minimum(b).print(); // or tf.minimum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction minimum_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'minimum');\n let $b = convertToTensor(b, 'b', 'minimum');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'bool') {\n $a = cast($a, 'int32');\n $b = cast($b, 'int32');\n }\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: MinimumInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Minimum, inputs as {} as NamedTensorMap);\n}\n\nexport const minimum = op({minimum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MirrorPad, MirrorPadAttrs, MirrorPadInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` using mirror padding.\n *\n * This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.\n *\n * ```js\n * const x = tf.range(0, 9).reshape([1, 1, 3, 3]);\n * x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * In \"reflect\" mode, the padded regions do not include the borders,\n * while in \"symmetric\" mode the padded regions do include the borders.\n * For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,\n * then the output is `[1, 2, 3, 2, 1]` in \"reflect\" mode, and\n * `[1, 2, 3, 3, 2]` in \"symmetric\" mode.\n * If `mode` is \"reflect\" then both `paddings[D, 0]` and `paddings[D, 1]`\n * must be no greater than `x.shape[D] - 1`. If mode is \"symmetric\"\n * then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than\n * `x.shape[D]`\n * @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`\n */\n/** @doc {heading: 'Tensors', subheading: 'Transformations'} */\nfunction mirrorPad_(\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_(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 {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,\n h: Array): [Tensor2D[], Tensor2D[]] {\n const $data = convertToTensor(data, 'data', 'multiRNNCell');\n const $c = convertToTensorArray(c, 'c', 'multiRNNCell');\n const $h = convertToTensorArray(h, 'h', 'multiRNNCell');\n\n let input = $data;\n const newStates = [];\n for (let i = 0; i < lstmCells.length; i++) {\n const output = lstmCells[i](input, $c[i], $h[i]);\n newStates.push(output[0]);\n newStates.push(output[1]);\n input = output[1];\n }\n const newC: Tensor2D[] = [];\n const newH: Tensor2D[] = [];\n for (let i = 0; i < newStates.length; i += 2) {\n newC.push(newStates[i]);\n newH.push(newStates[i + 1]);\n }\n return [newC, newH];\n}\nexport const multiRNNCell = op({multiRNNCell_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multinomial, MultinomialAttrs, MultinomialInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Creates a `tf.Tensor` with values drawn from a multinomial distribution.\n *\n * ```js\n * const probs = tf.tensor([.75, .25]);\n * tf.multinomial(probs, 3).print();\n * ```\n *\n * @param logits 1D array with unnormalized log-probabilities, or\n * 2D array of shape `[batchSize, numOutcomes]`. See the `normalized`\n * parameter.\n * @param numSamples Number of samples to draw for each row slice.\n * @param seed The seed number.\n * @param normalized Whether the provided `logits` are normalized true\n * probabilities (sum to 1). Defaults to false.\n * @return 1D array of shape `[numSamples]`, or 2D array of shape\n * `[batchSize, numSamples]`, depending on the rank of the input.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction multinomial_(\n logits: Tensor1D|Tensor2D|TensorLike, numSamples: number, seed?: number,\n normalized = false): Tensor1D|Tensor2D {\n const $logits = convertToTensor(logits, 'logits', 'multinomial');\n const numOutcomes = $logits.size;\n const origRank = $logits.rank;\n if (numOutcomes < 2) {\n throw new Error(\n `Error in multinomial: you need at least 2 outcomes, but got ` +\n `${numOutcomes}.`);\n }\n if (origRank > 2) {\n throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);\n }\n // TODO(lina128): Investigate correct seed behavior. The code seems not allow\n // setting see to 0.\n seed = seed || Math.random();\n\n // The kernel only accepts (and returns) rank 2 tensors.\n const logits2D: Tensor2D =\n origRank === 1 ? reshape($logits, [1, -1]) : $logits as Tensor2D;\n\n const inputs: MultinomialInputs = {logits: logits2D};\n const attrs: MultinomialAttrs = {numSamples, seed, normalized};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Multinomial, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor2D;\n\n // tslint:disable-next-line:no-unnecessary-type-assertion\n return origRank === 1 ? reshape(res, [res.size]) as Tensor1D : res;\n}\n\nexport const multinomial = op({multinomial_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {NotEqual, NotEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a != b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([0, 2, 3]);\n *\n * a.notEqual(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction notEqual_(\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 {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n * `indices` used to encode prediction class must start from 0. For example,\n * if you have 3 classes of data, class 1 should be encoded as 0, class 2\n * should be 1, and class 3 should be 2.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`. Indices must\n * start from 0.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n * not match the location.\n * @param dtype The dtype of the output tensor, default to 'int32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n indices: Tensor|TensorLike, depth: number, onValue = 1, offValue = 0,\n dtype: DataType = 'int32'): Tensor {\n if (depth < 2) {\n throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n }\n const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n\n const inputs: OneHotInputs = {indices: $indices};\n const attrs: OneHotAttrs = {dtype, depth, onValue, offValue};\n\n return ENGINE.runKernel(\n OneHot, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = op({oneHot_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OnesLike, OnesLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 1 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.onesLike(x).print();\n * ```\n * @param x A tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction onesLike_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'onesLike');\n\n const inputs: OnesLikeInputs = {x: $x};\n return ENGINE.runKernel(OnesLike, inputs as {} as NamedTensorMap);\n}\n\nexport const onesLike = op({onesLike_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the outer product of two vectors, `v1` and `v2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([3, 4, 5]);\n *\n * tf.outerProduct(a, b).print();\n * ```\n * @param v1 The first vector in the outer product operation.\n * @param v2 The second vector in the outer product operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction outerProduct_(\n v1: Tensor1D|TensorLike, v2: Tensor1D|TensorLike): Tensor2D {\n const $v1 = convertToTensor(v1, 'v1', 'outerProduct');\n const $v2 = convertToTensor(v2, 'v2', 'outerProduct');\n\n util.assert(\n $v1.rank === 1 && $v2.rank === 1,\n () => `Error in outerProduct: inputs must be rank 1, but got ranks ` +\n `${$v1.rank} and ${$v2.rank}.`);\n\n const v12D = reshape($v1, [-1, 1]);\n const v22D = reshape($v2, [1, -1]);\n return matMul(v12D, v22D);\n}\n\nexport const outerProduct = op({outerProduct_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {PadV2, PadV2Attrs, PadV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` with a given value and paddings.\n *\n * This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,\n * refer to `tf.mirrorPad`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `paddings` is of given length.\n * - `tf.pad1d`\n * - `tf.pad2d`\n * - `tf.pad3d`\n * - `tf.pad4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.pad([[1, 2]]).print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * @param constantValue The pad value to use. Defaults to 0.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction pad_(\n x: T|TensorLike, paddings: Array<[number, number]>, constantValue = 0): T {\n const $x = convertToTensor(x, 'x', 'pad');\n if ($x.rank === 0) {\n throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');\n }\n\n const attrs: PadV2Attrs = {paddings, constantValue};\n const inputs: PadV2Inputs = {x: $x};\n return ENGINE.runKernel(\n PadV2, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const pad = op({pad_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.\n */\nfunction pad1d_(\n x: Tensor1D|TensorLike, paddings: [number, number],\n constantValue = 0): Tensor1D {\n assert(\n paddings.length === 2,\n () => 'Invalid number of paddings. Must be length of 2.');\n return pad(x, [paddings], constantValue);\n}\n\nexport const pad1d = op({pad1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.\n */\nfunction pad2d_(\n x: Tensor2D|TensorLike, paddings: [[number, number], [number, number]],\n constantValue = 0): Tensor2D {\n assert(\n paddings.length === 2 && paddings[0].length === 2 &&\n paddings[1].length === 2,\n () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}\n\nexport const pad2d = op({pad2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.\n */\nfunction pad3d_(\n x: Tensor3D|TensorLike,\n paddings: [[number, number], [number, number], [number, number]],\n constantValue = 0): Tensor3D {\n assert(\n paddings.length === 3 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2,\n () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}\n\nexport const pad3d = op({pad3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.\n */\nfunction pad4d_(\n x: Tensor4D|TensorLike,\n paddings:\n [\n [number, number], [number, number], [number, number], [number, number]\n ],\n constantValue = 0): Tensor4D {\n assert(\n paddings.length === 4 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2 &&\n paddings[3].length === 2,\n () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}\n\nexport const pad4d = op({pad4d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation divides \"spatial\" dimensions `[1, ..., M]` of the input into\n * a grid of blocks of shape `blockShape`, and interleaves these blocks with\n * the \"batch\" dimension (0) such that in the output, the spatial\n * dimensions `[1, ..., M]` correspond to the position within the grid,\n * and the batch dimension combines both the position within a spatial block\n * and the original batch position. Prior to division into blocks,\n * the spatial dimensions of the input are optionally zero padded\n * according to `paddings`. See below for a precise description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);\n * const blockShape = [2, 2];\n * const paddings = [[0, 0], [0, 0]];\n *\n * x.spaceToBatchND(blockShape, paddings).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=\n * 0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad\n * from input dimension `i + 1`, which corresponds to spatial dimension `i`. It\n * is required that\n * `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input\n * according to `paddings` to produce `padded` of shape paddedShape.\n *\n * 2. Reshape `padded` to `reshapedPadded` of shape:\n * `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`\n *\n * 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`\n * of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the\n * batch dimension, producing an output tensor of shape:\n * `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction spaceToBatchND_(\n x: T|TensorLike, blockShape: number[], paddings: number[][]): T {\n const $x = convertToTensor(x, 'x', 'spaceToBatchND');\n\n util.assert(\n $x.rank >= 1 + blockShape.length,\n () => `input rank ${$x.rank} should be > than [blockShape] ${\n blockShape.length}`);\n\n util.assert(\n paddings.length === blockShape.length,\n () => `paddings.shape[0] ${\n paddings.length} must be equal to [blockShape] ${blockShape.length}`);\n\n util.assert(\n $x.shape.reduce(\n (a, b, i) => {\n if (i > 0 && i <= blockShape.length) {\n return a &&\n ((b + paddings[i - 1][0] + paddings[i - 1][1]) %\n blockShape[i - 1] ===\n 0);\n }\n return a;\n },\n true),\n () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${\n paddings.toString()} must be divisible by blockShapes ${\n blockShape.toString()}`);\n\n const inputs: SpaceToBatchNDInputs = {x: $x};\n const attrs: SpaceToBatchNDAttrs = {blockShape, paddings};\n\n return ENGINE.runKernel(\n SpaceToBatchND, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const spaceToBatchND = op({spaceToBatchND_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {avgPool} from './avg_pool';\nimport {batchToSpaceND} from './batch_to_space_nd';\nimport * as conv_util from './conv_util';\nimport {maxPool} from './max_pool';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {spaceToBatchND} from './space_to_batch_nd';\n\n/**\n * Performs an N-D pooling operation\n *\n * @param input The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param windowShape The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param poolingType The type of pooling, either 'max' or 'avg'.\n * @param pad The type of padding algorithm:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_guides/python/nn#Convolution](\n * https://www.tensorflow.org/api_guides/python/nn#Convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction pool_(\n input: T|TensorLike, windowShape: [number, number]|number,\n poolingType: 'avg'|'max',\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dilations?: [number, number]|number, strides?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil') {\n if (dilations == null) {\n dilations = [1, 1];\n }\n if (strides == null) {\n strides = 1;\n }\n if (pad === 0) {\n pad = 'valid';\n }\n\n const $x = convertToTensor(input, 'x', 'maxPool');\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in pool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = conv_util.computePool2DInfo(\n x4D.shape, windowShape, strides, dilations, pad);\n const dilation: [number, number] =\n [convInfo.dilationHeight, convInfo.dilationWidth];\n\n // The following implementation does batchToSpace(pool(spaceToBatch(x)))\n // whenever dilation > 1 since the TF kernels do not support dilation > 1.\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037\n\n let basePadding: number[][];\n if (pad === 'same') {\n basePadding = withSpaceToBatchBasePaddings(\n [convInfo.filterHeight, convInfo.filterWidth], dilation);\n } else {\n basePadding = [[0, 0], [0, 0]];\n }\n\n const isDilationOne = dilation[0] === 1 && dilation[1] === 1;\n const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings(\n [convInfo.inHeight, convInfo.inWidth], dilation, basePadding);\n const convertedPad = isDilationOne ? pad : 'valid';\n const convertedX =\n isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);\n\n const forwardOp = poolingType === 'avg' ?\n () => avgPool(convertedX, windowShape, strides, convertedPad,\n dimRoundingMode) :\n () => maxPool(convertedX, windowShape, strides, convertedPad,\n dimRoundingMode);\n const y = forwardOp();\n\n const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n\n return res as T;\n}\n\n// Helper function to compute crops and paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184\nfunction requiredSpaceToBatchPaddings(\n inputShape: [number, number], blockShape: [number, number],\n basePadding: number[][]) {\n const padStart = basePadding.map(b => b[0]);\n const origPadEnd = basePadding.map(b => b[1]);\n const fullInputShape = inputShape.concat(padStart, origPadEnd);\n const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);\n const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);\n const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);\n const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);\n return [paddings, crops];\n}\n\n// Helper function to compute base paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524\nfunction withSpaceToBatchBasePaddings(\n filterShape: [number, number], dilation: [number, number]) {\n // Spatial dimensions of the filters and the upsampled filters in which we\n // introduce (rate - 1) zeros between consecutive filter values.\n const dilatedFilterShape = filterShape.map((s, i) => {\n return s + (s - 1) * (dilation[i] - 1);\n });\n const padExtraShape = dilatedFilterShape.map(s => s - 1);\n\n // When padding is odd, we pad more at end, following the same\n // convention as conv2d.\n const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));\n const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);\n return padExtraShape.map((_, i) => {\n return [padExtraStart[i], padExtraEnd[i]];\n });\n}\n\nexport const pool = op({pool_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prelu, PreluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise with parametric alphas.\n *\n * `x < 0 ? alpha * x : f(x) = x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n * const alpha = tf.scalar(0.1);\n *\n * x.prelu(alpha).print(); // or tf.prelu(x, alpha)\n * ```\n * @param x The input tensor.\n * @param alpha Scaling factor for negative values.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction prelu_(x: T|TensorLike, alpha: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'prelu');\n const $alpha = convertToTensor(alpha, 'alpha', 'prelu');\n\n const inputs: PreluInputs = {x: $x, alpha: $alpha};\n return ENGINE.runKernel(Prelu, inputs as {} as NamedTensorMap);\n}\n\nexport const prelu = op({prelu_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prod, ProdAttrs, ProdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes the product of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.prod().print(); // or tf.prod(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.prod(axis).print(); // or tf.prod(x, axis)\n * ```\n *\n * @param x The input tensor to compute the product over. If the dtype is `bool`\n * it will be converted to `int32` and the output dtype will be `int32`.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction prod_(\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 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedGather, RaggedGatherAttrs, RaggedGatherInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather ragged slices from params axis 0 according to indices.\n *\n * @param paramsNestedSplits: A list of at least 1 Tensor with type 'int32' The\n * nestedRowSplits tensors that define the row-partitioning for the params\n * RaggedTensor input.\n * @param paramsDenseValues: A Tensor. The flatValues for the params\n * RaggedTensor.\n * @param indices: A Tensor. Must be one of type: int32. Indices in the\n * outermost dimension of params of the values that should be gathered.\n * @param outputRaggedRank: An int that is >= 0. The ragged rank of the output\n * RaggedTensor. outputNestedSplits will contain this number of rowSplits\n * tensors. This value should equal indices.shape.ndims + params.raggedRank\n * - 1.\n * @return A map with the following properties:\n * - outputNestedSplits: A list of outputRaggedRank Tensor objects with the\n * same type as paramsNestedSplits.\n * - outputDenseValues: A Tensor. Has the same type as paramsDenseValues.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\n\ninterface RaggedGatherMap {\n outputNestedSplits: Tensor[];\n outputDenseValues: Tensor;\n}\n\nfunction raggedGather_(\n paramsNestedSplits: Tensor[], paramsDenseValues: Tensor|TensorLike,\n indices: Tensor|TensorLike, outputRaggedRank: number): RaggedGatherMap {\n const $paramsNestedSplits = paramsNestedSplits.map(\n (t, i) => convertToTensor(t, `tensors${i}`, 'raggedGather', 'int32'));\n const $paramsDenseValues =\n convertToTensor(paramsDenseValues, 'paramsDenseValues', 'raggedGather');\n const $indices = convertToTensor(indices, 'indices', 'raggedGather', 'int32');\n\n const inputs: RaggedGatherInputs = {\n paramsNestedSplits: $paramsNestedSplits,\n paramsDenseValues: $paramsDenseValues,\n indices: $indices,\n };\n const attrs: RaggedGatherAttrs = {outputRaggedRank};\n\n const result: Tensor[] =\n ENGINE.runKernel(RaggedGather, inputs as {}, attrs as {});\n return {\n outputNestedSplits: result.slice(0, result.length - 1),\n outputDenseValues: result[result.length - 1],\n };\n}\n\nexport const raggedGather = op({raggedGather_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedTensorToTensor, RaggedTensorToTensorAttrs, RaggedTensorToTensorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Create a dense tensor from a ragged tensor, possibly altering its shape.\n *\n * The raggedTensorToTensor op creates a dense tensor from am array of row\n * partition tensors, a value vector, and default values. If the shape is\n * unspecified, the minimal shape required to contain all the elements in the\n * ragged tensor (the natural shape) will be used. If some dimensions are left\n * unspecified, then the size of the natural shape is used in that dimension.\n *\n * The defaultValue will be broadcast to the output shape. After that, the\n * values from the ragged tensor overwrite the default values. Note that the\n * defaultValue must have less dimensions than the value.\n *\n * The row partition tensors are in the order of the dimensions. At present, the\n * types can be: \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n * \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n * \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n * is preceded by \"FIRST_DIM_SIZE\".\n * ```\n * @param shape: A Tensor. Must be one of the following types: 'int32'. The\n * desired shape of the output tensor. If left unspecified (empty), the\n * minimal shape required to contain all the elements in the ragged tensor\n * (the natural shape) will be used. If some dimensions are left\n * unspecified, then the size of the natural shape is used in that\n * dimension.\n *\n * Note that dense dimensions cannot be modified by the shape argument.\n * Trying to change the size of a dense dimension will cause the op to fail.\n * Examples: natural shape: [4, 5, 6] shape: -1 output shape: [4, 5, 6]\n *\n * natural shape: [4, 5, 6] shape: [3, -1, 2] output shape: [3, 5, 2]\n *\n * natural shape: [4, 5, 6] shape: [3, 7, 2] output shape: [3, 7, 2]\n * @param values: A Tensor. A 1D tensor representing the values of the ragged\n * tensor.\n * @param defaultValue: A Tensor. Must have the same type as values. The\n * defaultValue when the shape is larger than the ragged tensor. The\n * defaultValue is broadcast until it is the shape of the output tensor,\n * and then overwritten by values in the ragged tensor. The default value\n * must be compatible with this broadcast operation, and must have fewer\n * dimensions than the value tensor.\n * @param rowPartitionTensors: A list of at least 1 Tensor objects with the same\n * type in: 'int32'.\n * @param rowPartitionTypes: A list of strings. The types of the row partition\n * tensors. At present, these can be:\n * \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n * \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n * \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then\n * it is preceeded by \"FIRST_DIM_SIZE\". The tensors are in the order of\n * the dimensions.\n * @return A Tensor. Has the same type as values.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\nfunction raggedTensorToTensor_(\n shape: Tensor|TensorLike, values: Tensor|TensorLike,\n defaultValue: Tensor|TensorLike, rowPartitionTensors: Tensor[],\n rowPartitionTypes: string[]): Tensor {\n const $shape =\n convertToTensor(shape, 'shape', 'raggedTensorToTensor', 'int32');\n const $values = convertToTensor(values, 'values', 'raggedTensorToTensor');\n const $defaultValue = convertToTensor(\n defaultValue, 'defaultValue', 'raggedTensorToTensor', $values.dtype);\n const $rowPartitionTensors = rowPartitionTensors.map(\n (t, i) =>\n convertToTensor(t, `tensors${i}`, 'raggedTensorToTensor', 'int32'));\n\n const inputs: RaggedTensorToTensorInputs = {\n shape: $shape,\n values: $values,\n defaultValue: $defaultValue,\n rowPartitionTensors: $rowPartitionTensors\n };\n const attrs: RaggedTensorToTensorAttrs = {rowPartitionTypes};\n\n return ENGINE.runKernel(RaggedTensorToTensor, inputs as {}, attrs as {});\n}\n\nexport const raggedTensorToTensor = op({raggedTensorToTensor_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {sizeFromShape} from '../util';\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_(\n shape: ShapeMap[R], randFunction: () => number,\n dtype?: DataType): Tensor {\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;\n}\n\nexport const rand = op({rand_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as seedrandom from 'seedrandom';\n\nimport {expectNumbersClose, testEpsilon} from '../test_util';\nimport {TypedArray} from '../types';\n\nexport interface RandomBase {\n nextValue(): number;\n}\n\nexport interface RandomGamma {\n nextValue(): number;\n}\n\nexport interface RandNormalDataTypes {\n float32: Float32Array;\n int32: Int32Array;\n}\n\nexport interface RandGammaDataTypes {\n float32: Float32Array;\n int32: Int32Array;\n}\n\n// https://en.wikipedia.org/wiki/Marsaglia_polar_method\nexport class MPRandGauss implements RandomBase {\n private mean: number;\n private stdDev: number;\n private nextVal: number;\n private dtype?: keyof RandNormalDataTypes;\n private truncated?: boolean;\n private upper?: number;\n private lower?: number;\n private random: seedrandom.prng;\n\n constructor(\n mean: number, stdDeviation: number, dtype?: keyof RandNormalDataTypes,\n truncated?: boolean, seed?: number) {\n this.mean = mean;\n this.stdDev = stdDeviation;\n this.dtype = dtype;\n this.nextVal = NaN;\n this.truncated = truncated;\n if (this.truncated) {\n this.upper = this.mean + this.stdDev * 2;\n this.lower = this.mean - this.stdDev * 2;\n }\n const seedValue = seed ? seed : Math.random();\n this.random = seedrandom.alea(seedValue.toString());\n }\n\n /** Returns next sample from a Gaussian distribution. */\n public nextValue(): number {\n if (!isNaN(this.nextVal)) {\n const value = this.nextVal;\n this.nextVal = NaN;\n return value;\n }\n\n let resultX: number, resultY: number;\n let isValid = false;\n while (!isValid) {\n let v1: number, v2: number, s: number;\n do {\n v1 = 2 * this.random() - 1;\n v2 = 2 * this.random() - 1;\n s = v1 * v1 + v2 * v2;\n } while (s >= 1 || s === 0);\n\n const mul = Math.sqrt(-2.0 * Math.log(s) / s);\n resultX = this.mean + this.stdDev * v1 * mul;\n resultY = this.mean + this.stdDev * v2 * mul;\n\n if (!this.truncated || this.isValidTruncated(resultX)) {\n isValid = true;\n }\n }\n\n if (!this.truncated || this.isValidTruncated(resultY)) {\n this.nextVal = this.convertValue(resultY);\n }\n return this.convertValue(resultX);\n }\n\n /** Handles proper rounding for non-floating-point numbers. */\n private convertValue(value: number): number {\n if (this.dtype == null || this.dtype === 'float32') {\n return value;\n }\n return Math.round(value);\n }\n\n /** Returns true if less than 2-standard-deviations from the mean. */\n private isValidTruncated(value: number): boolean {\n return value <= this.upper && value >= this.lower;\n }\n}\n\n// Marsaglia, George, and Wai Wan Tsang. 2000. \"A Simple Method for Generating\n// Gamma Variables.\"\nexport class RandGamma implements RandomGamma {\n private alpha: number;\n private beta: number;\n private d: number;\n private c: number;\n private dtype?: keyof RandGammaDataTypes;\n private randu: seedrandom.prng;\n private randn: MPRandGauss;\n\n constructor(\n alpha: number, beta: number, dtype: keyof RandGammaDataTypes,\n seed?: number) {\n this.alpha = alpha;\n this.beta = 1 / beta; // convert rate to scale parameter\n this.dtype = dtype;\n\n const seedValue = seed ? seed : Math.random();\n this.randu = seedrandom.alea(seedValue.toString());\n this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());\n\n if (alpha < 1) {\n this.d = alpha + (2 / 3);\n } else {\n this.d = alpha - (1 / 3);\n }\n this.c = 1 / Math.sqrt(9 * this.d);\n }\n\n /** Returns next sample from a gamma distribution. */\n public nextValue(): number {\n let x2: number, v0: number, v1: number, x: number, u: number, v: number;\n while (true) {\n do {\n x = this.randn.nextValue();\n v = 1 + (this.c * x);\n } while (v <= 0);\n v *= v * v;\n x2 = x * x;\n v0 = 1 - (0.331 * x2 * x2);\n v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));\n u = this.randu();\n if (u < v0 || Math.log(u) < v1) {\n break;\n }\n }\n v = (1 / this.beta) * this.d * v;\n if (this.alpha < 1) {\n v *= Math.pow(this.randu(), 1 / this.alpha);\n }\n return this.convertValue(v);\n }\n /** Handles proper rounding for non-floating-point numbers. */\n private convertValue(value: number): number {\n if (this.dtype === 'float32') {\n return value;\n }\n return Math.round(value);\n }\n}\n\nexport class UniformRandom implements RandomBase {\n private min: number;\n private range: number;\n private random: seedrandom.prng;\n private dtype?: keyof RandNormalDataTypes;\n\n constructor(\n min = 0, max = 1, dtype?: keyof RandNormalDataTypes,\n seed?: string|number) {\n this.min = min;\n this.range = max - min;\n this.dtype = dtype;\n if (seed == null) {\n seed = Math.random();\n }\n if (typeof seed === 'number') {\n seed = seed.toString();\n }\n\n if (!this.canReturnFloat() && this.range <= 1) {\n throw new Error(\n `The difference between ${min} - ${max} <= 1 and dtype is not float`);\n }\n this.random = seedrandom.alea(seed);\n }\n\n /** Handles proper rounding for non floating point numbers. */\n private canReturnFloat = () =>\n (this.dtype == null || this.dtype === 'float32');\n\n private convertValue(value: number): number {\n if (this.canReturnFloat()) {\n return value;\n }\n return Math.round(value);\n }\n\n nextValue() {\n return this.convertValue(this.min + this.range * this.random());\n }\n}\n\nexport function jarqueBeraNormalityTest(values: TypedArray|number[]) {\n // https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test\n const n = values.length;\n const s = skewness(values);\n const k = kurtosis(values);\n const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));\n // JB test requires 2-degress of freedom from Chi-Square @ 0.95:\n // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm\n const CHI_SQUARE_2DEG = 5.991;\n if (jb > CHI_SQUARE_2DEG) {\n throw new Error(`Invalid p-value for JB: ${jb}`);\n }\n}\n\nexport function expectArrayInMeanStdRange(\n actual: TypedArray|number[], expectedMean: number, expectedStdDev: number,\n epsilon?: number) {\n if (epsilon == null) {\n epsilon = testEpsilon();\n }\n const actualMean = mean(actual);\n expectNumbersClose(actualMean, expectedMean, epsilon);\n expectNumbersClose(\n standardDeviation(actual, actualMean), expectedStdDev, epsilon);\n}\n\nfunction mean(values: TypedArray|number[]) {\n let sum = 0;\n for (let i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum / values.length;\n}\n\nfunction standardDeviation(values: TypedArray|number[], mean: number) {\n let squareDiffSum = 0;\n for (let i = 0; i < values.length; i++) {\n const diff = values[i] - mean;\n squareDiffSum += diff * diff;\n }\n return Math.sqrt(squareDiffSum / values.length);\n}\n\nfunction kurtosis(values: TypedArray|number[]) {\n // https://en.wikipedia.org/wiki/Kurtosis\n const valuesMean = mean(values);\n const n = values.length;\n let sum2 = 0;\n let sum4 = 0;\n for (let i = 0; i < n; i++) {\n const v = values[i] - valuesMean;\n sum2 += Math.pow(v, 2);\n sum4 += Math.pow(v, 4);\n }\n return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);\n}\n\nfunction skewness(values: TypedArray|number[]) {\n // https://en.wikipedia.org/wiki/Skewness\n const valuesMean = mean(values);\n const n = values.length;\n let sum2 = 0;\n let sum3 = 0;\n for (let i = 0; i < n; i++) {\n const v = values[i] - valuesMean;\n sum2 += Math.pow(v, 2);\n sum3 += Math.pow(v, 3);\n }\n return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {RandGamma} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a gamma distribution.\n *\n * ```js\n * tf.randomGamma([2, 2], 1).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param alpha The shape parameter of the gamma distribution.\n * @param beta The inverse scale parameter of the gamma distribution. Defaults\n * to 1.\n * @param dtype The data type of the output. Defaults to float32.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomGamma_(\n shape: ShapeMap[R], alpha: number, beta = 1,\n dtype: 'float32'|'int32' = 'float32', seed?: number): Tensor {\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_(\n shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n seed?: number): Tensor {\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 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {op} from './operation';\nimport {randomNormal} from './random_normal';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * The generated values will have mean 0 and standard deviation 1.\n *\n * ```js\n * tf.randomStandardNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomStandardNormal_(\n shape: ShapeMap[R], dtype?: 'float32'|'int32', seed?: number): Tensor {\n if (dtype != null && (dtype as DataType) === 'bool') {\n throw new Error(`Unsupported data type ${dtype}`);\n }\n return randomNormal(shape, 0, 1, dtype, seed);\n}\n\nexport const randomStandardNormal = op({randomStandardNormal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\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_(\n shape: ShapeMap[R], minval = 0, maxval = 1, dtype: DataType = 'float32',\n seed?: number|string): Tensor {\n const res = buffer(shape, dtype);\n const random = new UniformRandom(minval, maxval, null, seed);\n for (let i = 0; i < res.values.length; i++) {\n res.values[i] = random.nextValue();\n }\n return res.toTensor();\n}\n\nexport const randomUniform = op({randomUniform_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Range, RangeAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Creates a new `tf.Tensor1D` filled with the numbers in the range provided.\n *\n * The tensor is a half-open interval meaning it includes start, but\n * excludes stop. Decrementing ranges and negative step values are also\n * supported.\n *\n *\n * ```js\n * tf.range(0, 9, 2).print();\n * ```\n *\n * @param start An integer start value\n * @param stop An integer stop value\n * @param step An integer increment (will default to 1 or -1)\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function range(\n start: number, stop: number, step = 1,\n dtype: 'float32'|'int32' = 'float32'): Tensor1D {\n if (step === 0) {\n throw new Error('Cannot have a step of zero');\n }\n\n const attrs: RangeAttrs = {start, stop, step, dtype};\n\n return ENGINE.runKernel(Range, {} /* inputs */, attrs as {} as NamedAttrMap);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Real, RealInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the real part of a complex (or real) tensor.\n *\n * Given a tensor input, this operation returns a tensor of type float that is\n * the real part of each element in input considered as a complex number.\n *\n * If the input is real, it simply makes a clone.\n *\n * ```js\n * const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);\n * tf.real(x).print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction real_(input: T|TensorLike): T {\n const $input = convertToTensor(input, 'input', 'real');\n\n const inputs: RealInputs = {input: $input};\n return ENGINE.runKernel(Real, inputs as {} as NamedTensorMap);\n}\n\nexport const real = op({real_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reciprocal, ReciprocalInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes reciprocal of x element-wise: `1 / x`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, 2]);\n *\n * x.reciprocal().print(); // or tf.reciprocal(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction reciprocal_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'reciprocal');\n\n const inputs: ReciprocalInputs = {x: $x};\n return ENGINE.runKernel(Reciprocal, inputs as {} as NamedTensorMap);\n}\nexport const reciprocal = op({reciprocal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu, ReluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear element-wise: `max(x, 0)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.relu().print(); // or tf.relu(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n * `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'relu');\n\n const inputs: ReluInputs = {x: $x};\n\n return ENGINE.runKernel(Relu, inputs as {} as NamedTensorMap);\n}\n\nexport const relu = op({relu_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu6, Relu6Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 8]);\n *\n * x.relu6().print(); // or tf.relu6(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n * `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu6_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'relu6');\n\n const inputs: Relu6Inputs = {x: $x};\n\n return ENGINE.runKernel(Relu6, inputs as {} as NamedTensorMap);\n}\n\nexport const relu6 = op({relu6_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reverse, ReverseAttrs, ReverseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reverses a `tf.Tensor` along a specified axis.\n *\n * Also available are stricter rank-specific methods that assert that `x` is\n * of the given rank:\n * - `tf.reverse1d`\n * - `tf.reverse2d`\n * - `tf.reverse3d`\n * - `tf.reverse4d`\n *\n * Except `tf.reverse1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.reverse().print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.reverse(axis).print();\n * ```\n * @param x The input tensor to be reversed.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction reverse_(\n x: T|TensorLike, axis?: number|number[]): T {\n const $x = convertToTensor(x, 'x', 'reverse');\n\n const inputs: ReverseInputs = {x: $x};\n const attrs: ReverseAttrs = {dims: axis};\n\n return ENGINE.runKernel(\n Reverse, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const reverse = op({reverse_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor1D`.\n *\n * @param x The input tensor.\n */\nfunction reverse1d_(x: Tensor1D|TensorLike): Tensor1D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 1,\n () => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);\n return reverse($x, 0);\n}\n\nexport const reverse1d = op({reverse1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor2D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse2d_(x: Tensor2D|TensorLike, axis?: number|number[]): Tensor2D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 2,\n () => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);\n return reverse($x, axis);\n}\n\nexport const reverse2d = op({reverse2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor3D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse3d_(x: Tensor3D|TensorLike, axis?: number|number[]): Tensor3D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 3,\n () => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);\n return reverse($x, axis);\n}\n\nexport const reverse3d = op({reverse3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor4D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse4d_(x: Tensor4D|TensorLike, axis?: number|number[]): Tensor4D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 4,\n () => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);\n return reverse($x, axis);\n}\n\nexport const reverse4d = op({reverse4d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Round, RoundInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes round of input `tf.Tensor` element-wise: `round(x)`.\n * It implements banker's rounding.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.round().print(); // or tf.round(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction round_(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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'rsqrt', 'float32');\n\n const inputs: RsqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Rsqrt, inputs as {} 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) : scale * x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.selu().print(); // or tf.selu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction selu_(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_(\n x: T|TensorLike, depthwiseFilter: Tensor4D|TensorLike,\n pointwiseFilter: Tensor4D|TensorLike, strides: [number, number]|number,\n pad: 'valid'|'same', dilation: [number, number]|number = [1, 1],\n dataFormat: 'NHWC'|'NCHW' = 'NHWC'): T {\n const $x = convertToTensor(x, 'x', 'separableConv2d');\n const $depthwiseFilter =\n convertToTensor(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');\n const $pointwiseFilter =\n convertToTensor(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n if (dataFormat === 'NCHW') {\n throw new Error(\n 'separableConv2d currently does not support dataFormat NCHW; only ' +\n 'NHWC is supported');\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in separableConv2d: input must be rank 4, but got ` +\n `rank ${x4D.rank}.`);\n util.assert(\n $depthwiseFilter.rank === 4,\n () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +\n `got rank ${$depthwiseFilter.rank}.`);\n util.assert(\n $pointwiseFilter.rank === 4,\n () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +\n `got rank ${$depthwiseFilter.rank}.`);\n util.assert(\n $pointwiseFilter.shape[0] === 1,\n () =>\n `Error in separableConv2d: the first dimension of pointwise filter ` +\n ` must be 1, but got ${$pointwiseFilter.shape[0]}.`);\n util.assert(\n $pointwiseFilter.shape[1] === 1,\n () => `Error in separableConv2d: the second dimension of pointwise ` +\n `filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);\n\n const inChannels = $depthwiseFilter.shape[2];\n const channelMultiplier = $depthwiseFilter.shape[3];\n util.assert(\n $pointwiseFilter.shape[2] === inChannels * channelMultiplier,\n () =>\n `Error in separableConv2d: the third dimension of pointwise filter ` +\n `must be ${inChannels * channelMultiplier}, ` +\n `but got ${$pointwiseFilter.shape[2]}.`);\n\n const depthwise = depthwiseConv2d(\n x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);\n const pointwiseStride = 1;\n const res =\n conv2d(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res as T;\n}\n\nexport const separableConv2d = op({separableConv2d_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, TensorBuffer} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\n/**\n * Computes the difference between two lists of numbers.\n *\n * Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`\n * that represents all values that are in `x` but not in `y`. The returned\n * Tensor `out` is sorted in the same order that the numbers appear in `x`\n * (duplicates are preserved). This operation also returns a Tensor indices that\n * represents the position of each out element in `x`. In other words:\n *\n * `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`\n *\n * ```js\n * const x = [1, 2, 3, 4, 5, 6];\n * const y = [1, 3, 5];\n *\n * const [out, indices] = await tf.setdiff1dAsync(x, y);\n * out.print(); // [2, 4, 6]\n * indices.print(); // [1, 3, 5]\n * ```\n *\n * @param x 1-D Tensor. Values to keep.\n * @param y 1-D Tensor. Must have the same type as x. Values to exclude in the\n * output.\n * @returns Promise of Tensor tuple [out, indices].\n * out: Tensor with the same type as x.\n * indices: A Tensor of type int32.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nasync function setdiff1dAsync_(\n x: Tensor|TensorLike, y: Tensor|TensorLike): Promise<[Tensor, Tensor]> {\n const $x = convertToTensor(x, 'x', 'setdiff1d');\n const $y = convertToTensor(y, 'y', 'setdiff1d');\n\n util.assert(\n $x.dtype === $y.dtype,\n () => `x and y should have the same dtype, but got x (${\n $x.dtype}) and y (${$y.dtype}).`);\n\n util.assert(\n $x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);\n\n util.assert(\n $y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);\n\n const xVals = await $x.data();\n const yVals = await $y.data();\n const ySet = new Set(yVals);\n\n let outputSize = 0;\n for (let i = 0; i < xVals.length; i++) {\n if (!ySet.has(xVals[i])) {\n outputSize++;\n }\n }\n\n const buffer = new TensorBuffer([outputSize], $x.dtype);\n const indices = new TensorBuffer([outputSize], 'int32');\n for (let i = 0, p = 0; i < xVals.length; i++) {\n if (!ySet.has(xVals[i])) {\n buffer.values[p] = xVals[i];\n indices.values[p] = i;\n p++;\n }\n }\n return [buffer.toTensor(), indices.toTensor()];\n}\nexport const setdiff1dAsync = setdiff1dAsync_;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sign, SignInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns an element-wise indication of the sign of a number.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);\n *\n * x.sign().print(); // or tf.sign(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sign_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sign');\n const inputs: SignInputs = {x: $x};\n return ENGINE.runKernel(Sign, inputs as {} as NamedTensorMap);\n}\nexport const sign = op({sign_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sin, SinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes sin of the input Tensor element-wise: `sin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.sin().print(); // or tf.sin(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sin_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sin', 'float32');\n\n const inputs: SinInputs = {x: $x};\n\n return ENGINE.runKernel(Sin, inputs as {} 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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sinh');\n const inputs: SinhInputs = {x: $x};\n\n return ENGINE.runKernel(Sinh, inputs as {} as NamedTensorMap);\n}\nexport const sinh = op({sinh_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 1D slice from 1D array starting at coordinates `begin` and is\n * of length `size`. See `slice` for details.\n */\nfunction slice1d_(\n x: Tensor1D|TensorLike, begin: number, size: number): Tensor1D {\n const $x = convertToTensor(x, 'x', 'slice1d');\n util.assert(\n $x.rank === 1,\n () =>\n `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, [begin], [size]);\n}\nexport const slice1d = op({slice1d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 2D slice from a 2D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice2d_(\n x: Tensor2D|TensorLike, begin: [number, number],\n size: [number, number]): Tensor2D {\n const $x = convertToTensor(x, 'x', 'slice2d');\n util.assert(\n $x.rank === 2,\n () =>\n `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, begin, size);\n}\nexport const slice2d = op({slice2d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 3D slice from a 3D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice3d_(\n x: Tensor3D|TensorLike, begin: [number, number, number],\n size: [number, number, number]): Tensor3D {\n const $x = convertToTensor(x, 'x', 'slice3d');\n util.assert(\n $x.rank === 3,\n () =>\n `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, begin, size);\n}\nexport const slice3d = op({slice3d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 4D slice from a 4D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice4d_(\n x: Tensor4D|TensorLike, begin: [number, number, number, number],\n size: [number, number, number, number]): Tensor4D {\n const $x = convertToTensor(x, 'x', 'slice4d');\n util.assert(\n $x.rank === 4,\n () =>\n `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, begin, size);\n}\nexport const slice4d = op({slice4d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softmax, SoftmaxAttrs, SoftmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the softmax normalized vector given the logits.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n *\n * a.softmax().print(); // or tf.softmax(a)\n * ```\n *\n * ```js\n * const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);\n *\n * a.softmax().print(); // or tf.softmax(a)\n * ```\n *\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n * which indicates the last dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction softmax_(logits: T|TensorLike, dim = -1): T {\n const $logits = convertToTensor(logits, 'logits', 'softmax', 'float32');\n\n if (dim === -1) {\n dim = $logits.rank - 1;\n }\n if (dim !== $logits.rank - 1) {\n throw Error(\n 'Softmax along a non-last dimension is not yet supported. ' +\n `Logits was rank ${$logits.rank} and dim was ${dim}`);\n }\n\n const inputs: SoftmaxInputs = {logits: $logits};\n const attrs: SoftmaxAttrs = {dim};\n\n return ENGINE.runKernel(\n Softmax, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const softmax = op({softmax_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FFT, FFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the inner-most\n * dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.fft().print(); // tf.spectral.fft(x).print();\n * ```\n * @param input The complex input to compute an fft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction fft_(input: Tensor): Tensor {\n assert(\n input.dtype === 'complex64',\n () => `The dtype for tf.spectral.fft() must be complex64 ` +\n `but got ${input.dtype}.`);\n\n const inputs: FFTInputs = {input};\n\n return ENGINE.runKernel(FFT, inputs as {} as NamedTensorMap);\n}\n\nexport const fft = op({fft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {IFFT, IFFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Inverse fast Fourier transform.\n *\n * Computes the inverse 1-dimensional discrete Fourier transform over the\n * inner-most dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.ifft().print(); // tf.spectral.ifft(x).print();\n * ```\n * @param input The complex input to compute an ifft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction ifft_(input: Tensor): Tensor {\n assert(\n input.dtype === 'complex64',\n () => `The dtype for tf.spectral.ifft() must be complex64 ` +\n `but got ${input.dtype}.`);\n\n const inputs: IFFTInputs = {input};\n\n return ENGINE.runKernel(IFFT, inputs as {} as NamedTensorMap);\n}\n\nexport const ifft = op({ifft_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {reverse} from '../reverse';\nimport {scalar} from '../scalar';\nimport {slice} from '../slice';\n\nimport {ifft} from './ifft';\n\n/**\n * Inversed real value input fast Fourier transform.\n *\n * Computes the 1-dimensional inversed discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([0, 0, 0]);\n * const x = tf.complex(real, imag);\n *\n * x.irfft().print();\n * ```\n * @param input The real value input to compute an irfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction irfft_(input: Tensor): Tensor {\n const innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = input.size / innerDimensionSize;\n let ret: Tensor;\n if (innerDimensionSize <= 2) {\n const complexInput = reshape(input, [batch, innerDimensionSize]);\n ret = ifft(complexInput);\n } else {\n // The length of unique components of the DFT of a real-valued signal\n // is 2 * (input_len - 1)\n const outputShape = [batch, 2 * (innerDimensionSize - 1)];\n const realInput = reshape(real(input), [batch, innerDimensionSize]);\n const imagInput = reshape(imag(input), [batch, innerDimensionSize]);\n\n const realConjugate =\n reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);\n const imagConjugate: Tensor2D = mul(\n reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1),\n scalar(-1));\n\n const r = concat([realInput, realConjugate], 1);\n const i = concat([imagInput, imagConjugate], 1);\n const complexInput =\n reshape(complex(r, i), [outputShape[0], outputShape[1]]);\n ret = ifft(complexInput);\n }\n ret = real(ret);\n // reshape the result if the input is 3D tensor.\n if (input.rank === 3 && input.shape[0] !== 0) {\n const temp = ret;\n const batch = input.shape[0];\n ret = reshape(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);\n temp.dispose();\n }\n return ret;\n}\n\nexport const irfft = op({irfft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {SplitV, SplitVAttrs, SplitVInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Splits a `tf.Tensor` into sub tensors.\n *\n * If `numOrSizeSplits` is a number, splits `x` along dimension `axis`\n * into `numOrSizeSplits` smaller tensors.\n * Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.\n *\n * If `numOrSizeSplits` is a number array, splits `x` into\n * `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the\n * same size as `x` except along dimension `axis` where the size is\n * `numOrSizeSplits[i]`.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);\n * const [a, b] = tf.split(x, 2, 1);\n * a.print();\n * b.print();\n *\n * const [c, d, e] = tf.split(x, [1, 2, 1], 1);\n * c.print();\n * d.print();\n * e.print();\n * ```\n *\n * @param x The input tensor to split.\n * @param numOrSizeSplits Either an integer indicating the number of\n * splits along the axis or an array of integers containing the sizes of\n * each output tensor along the axis. If a number then it must evenly divide\n * `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.\n * Can contain one -1 indicating that dimension is to be inferred.\n * @param axis The dimension along which to split. Defaults to 0 (the first\n * dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction split_(\n x: Tensor|TensorLike, numOrSizeSplits: number[]|number, axis = 0): T[] {\n const $x = convertToTensor(x, 'x', 'split');\n\n const inputs: SplitVInputs = {x: $x};\n const attr: SplitVAttrs = {numOrSizeSplits, axis};\n\n return ENGINE.runKernel(\n SplitV, inputs as {} as NamedTensorMap,\n attr as {} as NamedAttrMap) as {} as T[];\n}\n\nexport const split = op({split_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {assert} from '../../util';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {split} from '../split';\nimport {zeros} from '../zeros';\nimport {zerosLike} from '../zeros_like';\n\nimport {fft} from './fft';\n\n/**\n * Real value input fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n *\n * real.rfft().print();\n * ```\n * @param input The real value input to compute an rfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction rfft_(input: Tensor, fftLength?: number): Tensor {\n assert(\n input.dtype === 'float32',\n () => `The dtype for rfft() must be real value but got ${input.dtype}`);\n\n let innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = input.size / innerDimensionSize;\n\n let adjustedInput: Tensor;\n if (fftLength != null && fftLength < innerDimensionSize) {\n // Need to crop\n const begin = input.shape.map(v => 0);\n const size = input.shape.map(v => v);\n size[input.shape.length - 1] = fftLength;\n adjustedInput = slice(input, begin, size);\n innerDimensionSize = fftLength;\n } else if (fftLength != null && fftLength > innerDimensionSize) {\n // Need to pad with zeros\n const zerosShape = input.shape.map(v => v);\n zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;\n adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);\n innerDimensionSize = fftLength;\n } else {\n adjustedInput = input;\n }\n\n // Complement the input with zero imaginary numbers.\n const zerosInput = zerosLike(adjustedInput);\n const complexInput =\n reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);\n\n const ret = fft(complexInput);\n\n // Exclude complex conjugations. These conjugations are put symmetrically.\n const half = Math.floor(innerDimensionSize / 2) + 1;\n const realValues = real(ret);\n const imagValues = imag(ret);\n const realComplexConjugate = split(\n realValues, [half, innerDimensionSize - half],\n realValues.shape.length - 1);\n const imagComplexConjugate = split(\n imagValues, [half, innerDimensionSize - half],\n imagValues.shape.length - 1);\n\n const outputShape = adjustedInput.shape.slice();\n outputShape[adjustedInput.shape.length - 1] = half;\n\n return reshape(\n complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);\n}\n\nexport const rfft = op({rfft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'squaredDifference');\n let $b = convertToTensor(b, 'b', 'squaredDifference');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: SquaredDifferenceInputs = {a: $a, b: $b};\n const attrs = {};\n\n return ENGINE.runKernel(\n SquaredDifference, inputs as unknown as NamedTensorMap, attrs);\n}\n\nexport const squaredDifference = op({squaredDifference_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {squeezeShape} from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Removes dimensions of size 1 from the shape of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);\n * x.squeeze().print();\n * ```\n *\n * @param x The input tensor to be squeezed.\n * @param axis An optional list of numbers. If specified, only\n * squeezes the dimensions listed. The dimension index starts at 0. It\n * is an error to squeeze a dimension that is not 1.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction squeeze_(x: Tensor|TensorLike, axis?: number[]): T {\n const $x = convertToTensor(x, 'x', 'squeeze', 'string_or_numeric');\n return reshape($x, squeezeShape($x.shape, axis).newShape) as T;\n}\n\nexport const squeeze = op({squeeze_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Pack, PackAttrs, PackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.stack([a, b, c]).print();\n * ```\n *\n * @param tensors A list of tensor objects with the same shape and dtype.\n * @param axis The axis to stack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction stack_(\n tensors: Array, axis = 0): Tensor {\n const $tensors =\n convertToTensorArray(tensors, 'tensors', 'stack', 'string_or_numeric');\n\n util.assert(\n $tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');\n\n if ($tensors.length > 0) {\n util.assert(\n axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');\n }\n\n const inputs: PackInputs = $tensors;\n const attrs: PackAttrs = {axis};\n\n return ENGINE.runKernel(\n Pack, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const stack = op({stack_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Step, StepAttrs, StepInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha * x`\n *\n * ```js\n * const x = tf.tensor1d([0, 2, -1, -3]);\n *\n * x.step(.5).print(); // or tf.step(x, .5)\n * ```\n * @param x The input tensor.\n * @param alpha The gradient when input is negative.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction step_(x: T|TensorLike, alpha = 0.0): T {\n const $x = convertToTensor(x, 'x', 'step');\n\n const inputs: StepInputs = {x: $x};\n const attrs: StepAttrs = {alpha};\n\n return ENGINE.runKernel(\n Step, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\nexport const step = op({step_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {StridedSlice, StridedSliceAttrs, StridedSliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a strided slice of a tensor.\n *\n * Roughly speaking, this op extracts a slice of size (end-begin)/stride from\n * the given input tensor (x). Starting at the location specified by begin the\n * slice continues by adding stride to the index until all dimensions are not\n * less than end. Note that a stride can be negative, which causes a reverse\n * slice.\n *\n * ```js\n * const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],\n * [3, 2, 3]);\n * t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print() // [[[3, 3, 3]]]\n * t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print() // [[[3, 3, 3],\n * // [4, 4, 4]]]\n * t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],\n * // [3, 3, 3]]]\n * ```\n *\n * @param x The tensor to stride slice.\n * @param begin The coordinates to start the slice from.\n * @param end: The coordinates to end the slice at.\n * @param strides: The size of the slice.\n * @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored\n * and the fullest possible range in that dimension is used instead.\n * @param endMask: If the ith bit of endMask is set, end[i] is ignored\n * and the fullest possible range in that dimension is used instead.\n * @param shrinkAxisMask: a bitmask where bit i implies that\n * the ith specification should shrink the dimensionality. begin and end must\n * imply a slice of size 1 in the dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction stridedSlice_(\n x: Tensor|TensorLike, begin: number[], end: number[], strides?: number[],\n beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0,\n shrinkAxisMask = 0): Tensor {\n const $x = convertToTensor(x, 'x', 'stridedSlice', 'string_or_numeric');\n\n const inputs: StridedSliceInputs = {x: $x};\n const attrs: StridedSliceAttrs = {\n begin,\n end,\n strides,\n beginMask,\n endMask,\n ellipsisMask,\n newAxisMask,\n shrinkAxisMask\n };\n\n return ENGINE.runKernel(\n StridedSlice, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const stridedSlice = op({stridedSlice_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tan, TanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes tan of the input `tf.Tensor` element-wise, `tan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.tan().print(); // or tf.tan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tan_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'tan', 'float32');\n\n const inputs: TanInputs = {x: $x};\n\n return ENGINE.runKernel(Tan, inputs as {} as NamedTensorMap);\n}\nexport const tan = op({tan_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike1D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor1d` as it makes the code more readable.\n *\n * ```js\n * tf.tensor1d([1, 2, 3]).print();\n * ```\n *\n * @param values The values of the tensor. Can be array of numbers,\n * or a `TypedArray`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor1d(values: TensorLike1D, dtype?: DataType): Tensor1D {\n assertNonNull(values);\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 1) {\n throw new Error('tensor1d() requires values to be a flat/TypedArray');\n }\n const shape: number[] = null;\n return makeTensor(values, shape, inferredShape, dtype) as Tensor1D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike2D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor2d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor2d([[1, 2], [3, 4]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor2d(\n values: TensorLike2D, shape?: [number, number],\n dtype?: DataType): Tensor2D {\n assertNonNull(values);\n if (shape != null && shape.length !== 2) {\n throw new Error('tensor2d() requires shape to have two numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 2 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor2d() requires values to be number[][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor2d() requires shape to be provided when `values` ' +\n 'are a flat/TypedArray');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor2D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike3D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(\n values: TensorLike3D, shape?: [number, number, number],\n dtype?: DataType): Tensor3D {\n assertNonNull(values);\n if (shape != null && shape.length !== 3) {\n throw new Error('tensor3d() requires shape to have three numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor3d() requires values to be number[][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor3d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor3D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-4 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor4d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor4d(\n values: TensorLike4D, shape?: [number, number, number, number],\n dtype?: DataType): Tensor4D {\n assertNonNull(values);\n if (shape != null && shape.length !== 4) {\n throw new Error('tensor4d() requires shape to have four numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 4 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor4d() requires values to be number[][][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor4d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor4D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor5D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike5D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-5 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor5d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor5d([[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor5d(\n values: TensorLike5D, shape?: [number, number, number, number, number],\n dtype?: DataType): Tensor5D {\n assertNonNull(values);\n if (shape != null && shape.length !== 5) {\n throw new Error('tensor5d() requires shape to have five numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 5 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor5d() requires values to be ' +\n 'number[][][][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor5d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor5D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor6D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike6D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-6 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor6d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor6d([[[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor6d([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor6d(\n values: TensorLike6D,\n shape?: [number, number, number, number, number, number],\n dtype?: DataType): Tensor6D {\n assertNonNull(values);\n if (shape != null && shape.length !== 6) {\n throw new Error('tensor6d() requires shape to have six numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 6 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor6d() requires values to be number[][][][][][] or ' +\n 'flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor6d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n shape = shape ||\n inferredShape as [number, number, number, number, number, number];\n return makeTensor(values, shape, inferredShape, dtype) as Tensor6D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(\n x: T|TensorLike, k = 1, sorted = true): {values: T, indices: T} {\n const $x = convertToTensor(x, 'x', 'topk');\n if ($x.rank === 0) {\n throw new Error('topk() expects the input to be of rank 1 or higher');\n }\n const lastDim = $x.shape[$x.shape.length - 1];\n\n if (k < 0) {\n throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);\n }\n\n if (k > lastDim) {\n throw new Error(\n `'k' passed to topk() must be <= the last dimension (${lastDim}) ` +\n `but got ${k}`);\n }\n\n const inputs: TopKInputs = {x: $x};\n const attrs: TopKAttrs = {k, sorted};\n\n const [values, indices] = ENGINE.runKernel(\n TopK, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n\n return {values, indices} as {values: T, indices: T};\n}\n\nexport const topk = op({topk_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a truncated normal\n * distribution.\n *\n * ```js\n * tf.truncatedNormal([2, 2]).print();\n * ```\n *\n * The generated values follow a normal distribution with specified mean and\n * standard deviation, except that values whose magnitude is more than 2\n * standard deviations from the mean are dropped and re-picked.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output tensor.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction truncatedNormal_(\n shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n seed?: number): Tensor {\n if (dtype != null && (dtype as DataType) === 'bool') {\n throw new Error(`Unsupported data type $ { dtype }`);\n }\n const randGauss =\n new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);\n const res = buffer(shape, dtype);\n for (let i = 0; i < res.values.length; i++) {\n res.values[i] = randGauss.nextValue();\n }\n return res.toTensor();\n}\n\nexport const truncatedNormal = op({truncatedNormal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unique, UniqueAttrs, UniqueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Finds unique elements along an axis of a tensor.\n *\n * It returns a tensor `values` containing all of the unique elements along the\n * `axis` of the given tensor `x` in the same order that they occur along the\n * `axis` in `x`; `x` does not need to be sorted. It also returns a tensor\n * `indices` the same size as the number of the elements in `x` along the `axis`\n * dimension. It contains the index in the unique output `values`.\n *\n * ```js\n * // A 1-D tensor\n * const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);\n * const {values, indices} = tf.unique(a);\n * values.print(); // [1, 2, 4, 7, 8,]\n * indices.print(); // [0, 0, 1, 2, 2, 2, 3, 4, 4]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=0\n * //\n * // 'a' is: [[1, 0, 0],\n * // [1, 0, 0],\n * // [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 0)\n * values.print(); // [[1, 0, 0],\n * // [2, 0, 0]]\n * indices.print(); // [0, 0, 1]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=1\n * //\n * // 'a' is: [[1, 0, 0],\n * // [1, 0, 0],\n * // [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 1)\n * values.print(); // [[1, 0],\n * // [1, 0],\n * // [2, 0]]\n * indices.print(); // [0, 1, 1]\n * ```\n * @param x A tensor (int32, string, bool).\n * @param axis The axis of the tensor to find the unique elements.\n * @returns [uniqueElements, indices] (see above for details)\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction unique_(\n x: T|TensorLike, axis = 0): {values: T, indices: Tensor1D} {\n const $x = convertToTensor(x, 'x', 'unique', 'string_or_numeric');\n assert($x.rank > 0, () => 'The input tensor must be at least 1D');\n\n const inputs: UniqueInputs = {x: $x};\n const attrs: UniqueAttrs = {axis};\n const [values, indices] = ENGINE.runKernel(\n Unique, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as [T, Tensor1D];\n return {values, indices};\n}\n\nexport const unique = op({unique_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert, isInt} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Computes the sum along segments of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');\n * const numSegments = 3;\n *\n * x.unsortedSegmentSum(segmentIds, numSegments).print()\n * //or tf.unsortedSegmentSum(x, segmentIds, numSegments)\n * ```\n * @param x The `tf.Tensor` that will be summed along its segments.\n * @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s\n * dimension along the `axis`. Maps each element of `x` to a segment.\n * @param numSegments The number of distinct `segmentIds`.\n *\n * @doc {heading: 'Operations', subheading: 'Segment'}\n */\nfunction unsortedSegmentSum_(\n x: T|TensorLike, segmentIds: Tensor1D|TensorLike, numSegments: number): T {\n const $x = convertToTensor(x, 'x', 'unsortedSegmentSum');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');\n assert(isInt(numSegments), () => 'numSegments must be of dtype int');\n\n const inputs: UnsortedSegmentSumInputs = {x: $x, segmentIds: $segmentIds};\n const attrs: UnsortedSegmentSumAttrs = {numSegments};\n\n return ENGINE.runKernel(\n UnsortedSegmentSum, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const unsortedSegmentSum = op({unsortedSegmentSum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unpack, UnpackAttrs, UnpackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * tf.unstack(a).forEach(tensor => tensor.print());\n * ```\n *\n * @param x A tensor object.\n * @param axis The axis to unstack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction unstack_(x: Tensor|TensorLike, axis = 0): Tensor[] {\n const $x = convertToTensor(x, 'x', 'unstack', 'string_or_numeric');\n util.assert(\n axis >= -$x.shape.length && axis < $x.shape.length,\n () =>\n `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);\n\n const inputs: UnpackInputs = {value: $x};\n const attrs: UnpackAttrs = {axis};\n\n return ENGINE.runKernel(\n Unpack, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const unstack = op({unstack_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than the value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'upperBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * const values = tf.tensor1d([0, 4, 10]);\n * const result = tf.upperBound(seq, values);\n * result.print(); // [1, 2, 5]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n * applying upper bound to each value. The result is not a global index to\n * the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function upperBound(\n sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n return searchSorted(sortedSequence, values, 'right');\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor, Variable} from '../tensor';\nimport {DataType, Rank} from '../types';\n\n/**\n * Creates a new variable with the provided initial value.\n * ```js\n * const x = tf.variable(tf.tensor([1, 2, 3]));\n * x.assign(tf.tensor([4, 5, 6]));\n *\n * x.print();\n * ```\n *\n * @param initialValue Initial value for the tensor.\n * @param trainable If true, optimizers are allowed to update it.\n * @param name Name of the variable. Defaults to a unique id.\n * @param dtype If set, initialValue will be converted to the given type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function variable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n return ENGINE.makeVariable(initialValue, trainable, name, dtype) as\n Variable;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\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","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {\n const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');\n const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');\n\n const axisFrom = axis == null ? 0 : axis;\n const maskDim = $mask.rank;\n const tensorShape = $tensor.shape;\n\n util.assert(maskDim > 0, () => 'mask cannot be scalar');\n util.assertShapesMatch(\n tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape,\n `mask's shape must match the first K dimensions of tensor's shape,`);\n\n let leadingSize = 1;\n for (let i = axisFrom; i < axisFrom + maskDim; i++) {\n leadingSize *= tensorShape[i];\n }\n const targetTensorShape =\n tensorShape.slice(0, axisFrom)\n .concat([leadingSize], tensorShape.slice(axisFrom + maskDim));\n const reshapedTensor = reshape($tensor, targetTensorShape);\n const reshapedMask = reshape($mask, [-1]);\n const positivePositions = await whereAsync(reshapedMask);\n const indices = squeeze(positivePositions, [1]);\n\n const res = gather(reshapedTensor, indices, axisFrom);\n\n // Ensure no memory leak.\n if (tensor !== $tensor) {\n $tensor.dispose();\n }\n if (mask !== $mask) {\n $mask.dispose();\n }\n indices.dispose();\n reshapedTensor.dispose();\n reshapedMask.dispose();\n positivePositions.dispose();\n\n return res;\n}\n\nexport const booleanMaskAsync = booleanMaskAsync_;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n env().set('DEPRECATION_WARNINGS_ENABLED', false);\n console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n console.warn(\n msg + ' You can disable deprecation warnings with ' +\n 'tf.disableDeprecationWarnings().');\n }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n * (undisposed) at this time, which is ≤ the number of tensors\n * (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n * data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n * `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n * `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n * this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n * const x = tf.tensor1d([1, 2, 3]);\n * let x2 = x.square();\n * x2.dispose();\n * x2 = x.square();\n * x2.dispose();\n * return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise)):\n Promise {\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(\n nameOrFn: string|ScopeFn, fn?: ScopeFn): 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(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 {\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 {\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 {\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 {\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,\n priority = 1): boolean {\n return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n env().setPlatform(platformName, platform);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {tidy} from '../globals';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {complex} from './complex';\nimport {imag} from './imag';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {real} from './real';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print(); // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n * @param conjugate Will conjugate complex input if true.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_(\n x: T|TensorLike, perm?: number[], conjugate?: boolean): T {\n const $x = convertToTensor(x, 'x', 'transpose');\n\n if (perm == null) {\n perm = $x.shape.map((s, i) => i).reverse();\n }\n util.assert(\n $x.rank === perm.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of perm ${perm}.`);\n perm.forEach(axis => {\n util.assert(\n axis >= 0 && axis < $x.rank,\n () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n ` but got ${perm}`);\n });\n\n if ($x.rank <= 1) {\n return $x.clone();\n }\n\n const inputs: TransposeInputs = {x: $x};\n const attrs: TransposeAttrs = {perm};\n\n if ($x.dtype === 'complex64') {\n return tidy(() => {\n let $real = real($x);\n let $imag = imag($x);\n $real = ENGINE.runKernel(\n Transpose, {x: $real} as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n $imag = ENGINE.runKernel(\n Transpose, {x: $imag} as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n if (conjugate) {\n $imag = neg($imag);\n }\n return complex($real, $imag);\n });\n }\n\n return ENGINE.runKernel(\n Transpose, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const transpose = op({transpose_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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_(\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 */\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(\n indices: Tensor|TensorLike, updates: Tensor|TensorLike,\n shape: ShapeMap[R]): Tensor {\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;\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 */\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_(\n sparseIndices: Tensor|TensorLike, sparseValues: Tensor|TensorLike,\n outputShape: ShapeMap[R], defaultValue: Scalar|ScalarLike = 0): Tensor {\n const $sparseIndices =\n convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');\n const $sparseValues = convertToTensor(\n sparseValues, 'sparseValues', 'sparseToDense', 'string_or_numeric');\n const $defaultValue = convertToTensor(\n defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);\n\n sparse_to_dense.validateInput(\n $sparseIndices, $sparseValues, outputShape, $defaultValue);\n\n const inputs: SparseToDenseInputs = {\n sparseIndices: $sparseIndices,\n sparseValues: $sparseValues,\n defaultValue: $defaultValue\n };\n\n const attrs: SparseToDenseAttrs = {outputShape};\n\n return ENGINE.runKernel(\n SparseToDense, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const sparseToDense = op({sparseToDense_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {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 */\nimport {ENGINE} from '../engine';\nimport {GatherNd, GatherNdInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather slices from input tensor into a Tensor with shape specified by\n * `indices`.\n *\n * `indices` is a K-dimensional integer tensor, best thought of as a\n * (K-1)-dimensional tensor of indices into input, where each element defines a\n * slice of input:\n * output[\\\\(i_0, ..., i_{K-2}\\\\)] = input[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n *\n * Whereas in `tf.gather`, `indices` defines slices into the first dimension of\n * input, in `tf.gatherND`, `indices` defines slices into the first N dimensions\n * of input, where N = indices.shape[-1].\n *\n * The last dimension of indices can be at most the rank of input:\n * indices.shape[-1] <= input.rank\n *\n * The last dimension of `indices` corresponds to elements\n * (if indices.shape[-1] == input.rank) or slices\n * (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of\n * input.\n * The output tensor has shape\n * indices.shape[:-1] + input.shape[indices.shape[-1]:]\n *\n * Note that on CPU, if an out of bound index is found, an error is returned. On\n * GPU, if an out of bound index is found, a 0 is stored in the corresponding\n * output value.\n *\n * ```js\n * const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');\n * const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);\n * tf.gatherND(input, indices).print() // [10, 11]\n * ```\n *\n * @param x The tensor from which to gather values.\n * @param indices Index tensor, must be of type int32.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction gatherND_(x: Tensor|TensorLike, indices: Tensor|TensorLike): Tensor {\n const $indices = convertToTensor(indices, 'indices', 'gatherND', 'int32');\n const $x = convertToTensor(x, 'x', 'gatherND', 'string_or_numeric');\n\n const inputs: GatherNdInputs = {params: $x, indices: $indices};\n\n return ENGINE.runKernel(GatherNd, inputs as {} as NamedTensorMap);\n}\n\nexport const gatherND = op({gatherND_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_(\n predictions: T|TensorLike, targets: U|TensorLike, k = 1): Promise {\n const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');\n const $targets = convertToTensor(targets, 'targets', 'inTopK');\n\n assert(\n $predictions.rank > 1,\n () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +\n `but got ${$predictions.rank}`);\n assert(\n $predictions.rank - 1 === $targets.rank,\n () => `predictions rank should be 1 larger than ` +\n `targets rank, but got predictions rank ` +\n `${$predictions.rank} and targets rank ${$targets.rank}`);\n assertShapesMatch(\n $predictions.shape.slice(0, $predictions.shape.length - 1),\n $targets.shape,\n `predictions's shape should be align with the targets' shape, ` +\n 'except the last dimension.');\n const lastDim = $predictions.shape[$predictions.shape.length - 1];\n assert(\n k > 0 && k <= lastDim,\n () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +\n `dimension (${lastDim}), but got ${k}`);\n\n const predictionsVals = await $predictions.data();\n const targetsVals = await $targets.data();\n\n // Reshape predictionsVals into a 2d tensor [batch, lastDim]\n // and look up topK along lastDim.\n const [batch, size] = [predictionsVals.length / lastDim, lastDim];\n const precision = getTypedArrayFromDType('bool', batch);\n\n for (let b = 0; b < batch; b++) {\n const offset = b * size;\n const vals = predictionsVals.subarray(offset, offset + size);\n const valAndInd: Array<{value: number, index: number}> = [];\n for (let i = 0; i < vals.length; i++) {\n valAndInd.push({value: vals[i], index: i});\n }\n valAndInd.sort((a, b) => b.value - a.value);\n\n precision[b] = 0;\n for (let i = 0; i < k; i++) {\n if (valAndInd[i].index === targetsVals[b]) {\n precision[b] = 1;\n break;\n }\n }\n }\n\n if (predictions !== $predictions) {\n $predictions.dispose();\n }\n if (targets !== $targets) {\n $targets.dispose();\n }\n\n // Output precision has the same shape as targets.\n return tensor(precision, $targets.shape, 'bool') as U;\n}\n\nexport const inTopKAsync = inTopKAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the filter of a 2D convolution.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.\n * @param dy The dy image, of rank 4 or rank 3, of shape\n * [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.\n * @param filterShape The shape of the filter, length 4,\n * [filterHeight, filterWidth, inDepth, outDepth].\n * @param strides The strides of the convolution: [strideHeight,\n * strideWidth].\n * @param pad A string from: 'same', 'valid'. The type of padding algorithm\n * used in the forward prop of the op.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction conv2DBackpropFilter_(\n x: T, dy: T, filterShape: [number, number, number, number],\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n let x4D = x as Tensor4D;\n if (x.rank === 3) {\n x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n }\n let dy4D = dy as Tensor4D;\n if (dy4D.rank === 3) {\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +\n `${x4D.shape}.`);\n util.assert(\n dy4D.rank === 4,\n () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +\n `${dy4D.shape}.`);\n util.assert(\n filterShape.length === 4,\n () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +\n `${filterShape}.`);\n const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n util.assert(\n inDepth === filterShape[2],\n () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +\n `match input depth in filter (${filterShape[2]}.`);\n util.assert(\n outDepth === filterShape[3],\n () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +\n `match output depth for filter (${filterShape[3]}).`);\n conv_util.checkPadOnDimRoundingMode('conv2dDerFilter', pad, dimRoundingMode);\n const inputs: Conv2DBackpropFilterInputs = {x: x4D, dy: dy4D};\n const attrs: Conv2DBackpropFilterAttrs =\n {strides, pad, dataFormat, dimRoundingMode, filterShape};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n Conv2DBackpropFilter, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor4D;\n}\n\nexport const conv2DBackpropFilter = op({conv2DBackpropFilter_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\nimport * as broadcast_util from './broadcast_util';\nimport {elu} from './elu';\nimport {Activation} from './fused_types';\nimport {leakyRelu} from './leaky_relu';\nimport {mul} from './mul';\nimport {prelu} from './prelu';\nimport {relu} from './relu';\nimport {relu6} from './relu6';\nimport {reshape} from './reshape';\nimport {sigmoid} from './sigmoid';\nimport {step} from './step';\nimport {sum} from './sum';\n\n// Returns gradient for fused activation.\nexport function getFusedDyActivation(\n dy: Tensor, y: Tensor, activation: Activation): Tensor {\n if (activation == null || activation === 'linear') {\n return dy;\n }\n if (activation === 'relu') {\n return mul(dy, step(y));\n }\n throw new Error(\n `Cannot compute gradient for fused activation ${activation}.`);\n}\n\n// Returns gradient for fused bias.\nexport function getFusedBiasGradient(\n bias: Tensor, dyActivation: Tensor): Tensor {\n let res = dyActivation;\n const reduceAxes =\n broadcast_util.getReductionAxes(bias.shape, dyActivation.shape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, bias.shape);\n}\n\nexport function applyActivation(\n x: Tensor, activation: Activation, preluActivationWeights?: Tensor,\n leakyreluAlpha?: number): Tensor {\n if (activation === 'linear') {\n return x;\n } else if (activation === 'relu') {\n return relu(x);\n } else if (activation === 'elu') {\n return elu(x);\n } else if (activation === 'relu6') {\n return relu6(x);\n } else if (activation === 'prelu') {\n return prelu(x, preluActivationWeights);\n } else if (activation === 'leakyrelu') {\n return leakyRelu(x, leakyreluAlpha);\n } else if (activation === 'sigmoid') {\n return sigmoid(x);\n }\n throw new Error(`Unknown fused activation ${activation}.`);\n}\n\n// Whether we should call fused ops.\nexport const shouldFuse = (gradientDepth: number, activation: Activation) => {\n const gradientMode = gradientDepth > 0;\n return !gradientMode || activation === 'linear';\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {conv2d as unfusedConv2d} from '../conv2d';\nimport {conv2DBackpropFilter} from '../conv2d_backprop_filter';\nimport {conv2DBackpropInput} from '../conv2d_backprop_input';\nimport * as conv_util from '../conv_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes a 2D convolution over the input x, optionally fused with adding a\n * bias and applying an activation.\n *\n * ```js\n * const inputDepth = 2;\n * const inShape = [2, 2, 2, inputDepth];\n * const outputDepth = 2;\n * const fSize = 1;\n * const pad = 0;\n * const strides = 1;\n *\n * const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n * 16], inShape);\n * const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,\n * outputDepth]);\n *\n * tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',\n * dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();\n * ```\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid` output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`) to be\n * applied\n * after biasAdd.\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n * of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n * activation.\n */\nfunction fusedConv2d_({\n x,\n filter,\n strides,\n pad,\n dataFormat = 'NHWC',\n dilations = [1, 1],\n dimRoundingMode,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha\n}: {\n x: T|TensorLike,\n filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n bias?: Tensor|TensorLike,\n activation?: Activation,\n preluActivationWeights?: Tensor,\n leakyreluAlpha?: number\n}): T {\n activation = activation || 'linear';\n\n if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n // TODO: Transpose bias and preluActivationWeights properly for NCHW\n // format before computation.\n util.assert(\n dataFormat === 'NHWC',\n () => `Error in fused conv2d: got dataFormat of ${dataFormat} but ` +\n `only NHWC is currently supported for the case of gradient depth ` +\n `is 0 and the activation is not linear.`);\n\n let result = unfusedConv2d(\n x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha) as T;\n }\n\n const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in fused conv2d: input must be rank 4, but got rank ` +\n `${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in fused conv2d: filter must be rank 4, but got rank ` +\n `${$filter.rank}.`);\n conv_util.checkPadOnDimRoundingMode('fused conv2d', pad, dimRoundingMode);\n const inputChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n util.assert(\n $filter.shape[2] === inputChannels,\n () => `Error in conv2d: depth of input (${inputChannels}) must match ` +\n `input depth for filter ${$filter.shape[2]}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = conv_util.computeConv2DInfo(\n x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);\n\n let $bias: Tensor;\n if (bias != null) {\n $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n [$bias] = makeTypesMatch($bias, $x);\n\n // According to TensorFlow, the bias is supposed be a 1-D tensor or a\n // scalar.\n //\n // 3-D or 4-D bias is not disabled for NHWC format, because they are\n // currently being used in some cases. For examplem in our code base,\n // https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/fused_conv2d_test.ts#L1972.\n if (dataFormat === 'NHWC') {\n broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n } else {\n util.assert(\n $bias.shape.length <= 1,\n () => `Error in fused conv2d: only supports scalar or 1-D Tensor ` +\n `bias for NCHW format but got the bias of ` +\n `rank-${$bias.shape.length}.`);\n\n util.assert(\n $bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels ||\n $bias.shape[0] === 1,\n () => `Error in fused conv2d: bias shape (${$bias.shape}) is not ` +\n `compatible with the number of output channels ` +\n `(${convInfo.outChannels})`);\n }\n }\n\n let $preluActivationWeights: Tensor;\n if (preluActivationWeights != null) {\n // PReLU's activation weights could be a scalar, a 1-D tensor or a 3-D\n // tensor.\n const alphaShape = preluActivationWeights.shape;\n util.assert(\n alphaShape.length <= 1 || alphaShape.length === 3,\n () => `Error in fused conv2d: only supports scalar, 1-D Tensor or ` +\n `3-D Tensor PReLU activation weights but got a tensor of ` +\n `rank-${alphaShape.length}.`);\n\n if (alphaShape.length === 1) {\n // Whether the data format is NCHW or NHWC, the 1-D PReLU activation\n // weights tensor should be aligned with the output channels of conv2d\n // result.\n util.assert(\n alphaShape[0] === 1 || alphaShape[0] === convInfo.outChannels,\n () => `Error in fused conv2d: PReLU activation weights ` +\n `(${alphaShape}) is not compatible with the number of output ` +\n `channels (${convInfo.outChannels}).`);\n } else if (alphaShape.length === 3) {\n // Whether the data format is NCHW or NHWC, the PReLU activation weights\n // tensor should has the compatible shape with the result of conv2d.\n try {\n broadcast_util.assertAndGetBroadcastShape(\n alphaShape, convInfo.outShape);\n } catch (e) {\n const errMsg =\n `Error in fused conv2d: PReLU activation weights (${alphaShape}) ` +\n `is not compatible with the output shape of the conv2d ` +\n `(${convInfo.outShape}).`;\n throw Error(errMsg);\n }\n }\n\n $preluActivationWeights = convertToTensor(\n preluActivationWeights, 'prelu weights', 'fused conv2d');\n }\n\n const grad = (dy: Tensor4D, saved: Tensor[]) => {\n util.assert(\n dataFormat === 'NHWC',\n () => `Error in gradient of fused conv2D: got dataFormat of ${\n dataFormat} but only NHWC is currently supported.`);\n\n const [$filter, x4D, y, $bias] =\n saved as [Tensor4D, Tensor4D, Tensor4D, Tensor];\n\n const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n util.assert(\n conv_util.tupleValuesAreOne(dilations),\n () => 'Error in gradient of fused conv2D: ' +\n `dilation rates greater than 1 ` +\n `are not yet supported in gradients. Got dilations '${dilations}'`);\n\n const xDer =\n conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad);\n const filterDer =\n conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad);\n const der: Tensor[] = [xDer, filterDer];\n\n if ($bias != null) {\n const biasDer = getFusedBiasGradient($bias, dyActivation);\n der.push(biasDer);\n }\n return der;\n };\n\n const inputs: FusedConv2DInputs = {\n x: x4D,\n filter: $filter,\n bias: $bias,\n preluActivationWeights: $preluActivationWeights\n };\n\n const attrs: FusedConv2DAttrs = {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n };\n\n // Depending on the the params passed in we will have different number of\n // inputs and thus a a different number of elements in the gradient.\n if (bias == null) {\n const customOp =\n customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n let res: Tensor4D|Tensor3D =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n FusedConv2D, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n\n save([filter, x4D, res]);\n\n if (reshapedTo4D) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n Tensor3D;\n }\n\n return {value: res, gradFunc: grad};\n });\n return customOp(x4D, $filter) as T;\n } else {\n const customOpWithBias = customGrad(\n (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n FusedConv2D, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n\n save([filter, x4D, res, bias]);\n\n if (reshapedTo4D) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n Tensor3D;\n }\n\n return {value: res, gradFunc: grad};\n });\n\n return customOpWithBias(x4D, $filter, $bias) as T;\n }\n}\nexport const conv2d = op({fusedConv2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropFilter_(\n x: T, dy: T, filterShape: [number, number, number, number],\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n let x4D = x as Tensor4D;\n if (x.rank === 3) {\n x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n }\n let dy4D = dy as Tensor4D;\n if (dy4D.rank === 3) {\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n }\n\n const inputs: DepthwiseConv2dNativeBackpropFilterInputs = {x: x4D, dy: dy4D};\n const attrs: DepthwiseConv2dNativeBackpropFilterAttrs =\n {strides, pad, dimRoundingMode, dilations, filterShape};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n DepthwiseConv2dNativeBackpropFilter,\n inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap) as\n Tensor4D;\n}\n\nexport const depthwiseConv2dNativeBackpropFilter =\n op({depthwiseConv2dNativeBackpropFilter_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropInput_(\n xShape: [number, number, number, number], dy: T, filter: Tensor4D,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n let dy4D = dy as Tensor4D;\n let reshapedTo4D = false;\n if (dy.rank === 3) {\n reshapedTo4D = true;\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n }\n\n const inputs: DepthwiseConv2dNativeBackpropInputInputs = {dy: dy4D, filter};\n const attrs: DepthwiseConv2dNativeBackpropInputAttrs =\n {strides, pad, dimRoundingMode, dilations, inputShape: xShape};\n\n const res =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n DepthwiseConv2dNativeBackpropInput, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const depthwiseConv2dNativeBackpropInput =\n op({depthwiseConv2dNativeBackpropInput_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\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_({\n x,\n filter,\n strides,\n pad,\n dataFormat = 'NHWC',\n dilations = [1, 1],\n dimRoundingMode,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha\n}: {\n x: T|TensorLike,\n filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number,\n dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n bias?: Tensor|TensorLike,\n activation?: Activation,\n preluActivationWeights?: Tensor,\n leakyreluAlpha?: number\n}): T {\n if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n let result = unfusedDepthwiseConv2d(\n x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha) as T;\n }\n\n const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n const $filter =\n convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in fused depthwiseConv2d: input must be rank 4, but got ` +\n `rank ${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in fused depthwiseConv2d: filter must be rank 4, ` +\n `but got rank ${$filter.rank}.`);\n util.assert(\n x4D.shape[3] === $filter.shape[2],\n () => `Error in fused depthwiseConv2d: number of input channels ` +\n `(${x4D.shape[3]}) must match the inChannels dimension in ` +\n `filter ${$filter.shape[2]}.`);\n if (dilations == null) {\n dilations = [1, 1];\n }\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () =>\n 'Error in fused depthwiseConv2d: Either strides or dilations must ' +\n `be 1. Got strides ${strides} and dilations '${dilations}'`);\n conv_util.checkPadOnDimRoundingMode(\n 'fused depthwiseConv2d', pad, dimRoundingMode);\n const convInfo = conv_util.computeConv2DInfo(\n x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode,\n true /* depthwise */);\n\n let $bias: Tensor;\n if (bias != null) {\n $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n [$bias] = makeTypesMatch($bias, $x);\n\n broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n }\n\n let $preluActivationWeights: Tensor;\n if (preluActivationWeights != null) {\n $preluActivationWeights = convertToTensor(\n preluActivationWeights, 'prelu weights', 'fused depthwiseConv2d');\n }\n\n const grad = (dy: Tensor4D, saved: Tensor[]) => {\n util.assert(\n conv_util.tupleValuesAreOne(dilations),\n () => 'Error in gradient of fused depthwiseConv2d: dilation rates ' +\n `greater than 1 are not yet supported. Got dilations ` +\n `'${dilations}'`);\n const [$filter, x4D, y, bias] = saved;\n\n const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n const xDer = depthwiseConv2dNativeBackpropInput(\n (x4D as Tensor4D).shape, dyActivation, $filter as Tensor4D, strides,\n pad, dilations, dimRoundingMode);\n const filterDer = depthwiseConv2dNativeBackpropFilter(\n x4D as Tensor4D, dyActivation, ($filter as Tensor4D).shape, strides,\n pad, dilations, dimRoundingMode);\n\n if (bias != null) {\n const biasDer = getFusedBiasGradient($bias, dyActivation);\n return [xDer, filterDer, biasDer];\n }\n return [xDer, filterDer];\n };\n\n const inputs: FusedDepthwiseConv2DInputs = {\n x: x4D,\n filter: $filter,\n bias: $bias,\n preluActivationWeights: $preluActivationWeights\n };\n const attrs: FusedDepthwiseConv2DAttrs = {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n };\n\n // Depending on the the params passed in we will have different number of\n // inputs and thus a a different number of elements in the gradient.\n if (bias == null) {\n const customOp =\n customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n FusedDepthwiseConv2D, inputs as {} 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_({\n a,\n b,\n transposeA = false,\n transposeB = false,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha = 0.2,\n}: {\n a: Tensor|TensorLike,\n b: Tensor|TensorLike,\n transposeA?: boolean,\n transposeB?: boolean,\n bias?: Tensor|TensorLike,\n activation?: Activation,\n preluActivationWeights?: Tensor\n leakyreluAlpha?: number\n}): Tensor {\n if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n let result = unfusedMatMul(a, b, transposeA, transposeB);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha);\n }\n\n let $a = convertToTensor(a, 'a', 'fused matMul');\n let $b = convertToTensor(b, 'b', 'fused matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const innerShapeA =\n transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];\n const innerShapeB =\n transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];\n\n const outerShapeA =\n transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];\n const outerShapeB =\n transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];\n\n const outerDimsA = $a.shape.slice(0, -2);\n const outerDimsB = $b.shape.slice(0, -2);\n const batchDimA = util.sizeFromShape(outerDimsA);\n const batchDimB = util.sizeFromShape(outerDimsB);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in fused matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n $a.shape.slice(0, -2), $b.shape.slice(0, -2));\n const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n const a3D: Tensor3D = transposeA ?\n reshape($a, [batchDimA, innerShapeA, outerShapeA]) :\n reshape($a, [batchDimA, outerShapeA, innerShapeA]);\n const b3D: Tensor3D = transposeB ?\n reshape($b, [batchDimB, outerShapeB, innerShapeB]) :\n reshape($b, [batchDimB, innerShapeB, outerShapeB]);\n\n let $bias: Tensor;\n if (bias != null) {\n $bias = convertToTensor(bias, 'bias', 'fused matMul');\n [$bias] = makeTypesMatch($bias, $a);\n\n broadcast_util.assertAndGetBroadcastShape(outShape, $bias.shape);\n }\n\n let $preluActivationWeights: Tensor;\n if (preluActivationWeights != null) {\n $preluActivationWeights = convertToTensor(\n preluActivationWeights, 'prelu weights', 'fused matMul');\n }\n\n const grad = (dy: Tensor3D, saved: Tensor[]) => {\n const [a3D, b3D, y, $bias] = saved;\n // we reshape dy because the result of the forward is not\n // necessarily going to be a 3d tensor due to a reshape done at the end of\n // the customOp.\n const dyActivation =\n getFusedDyActivation(reshape(dy, y.shape), y, activation);\n let aDer: Tensor;\n let bDer: Tensor;\n\n if (!transposeA && !transposeB) {\n aDer = unfusedMatMul(dyActivation, b3D, false, true);\n bDer = unfusedMatMul(a3D, dyActivation, true, false);\n } else if (!transposeA && transposeB) {\n aDer = unfusedMatMul(dyActivation, b3D, false, false);\n bDer = unfusedMatMul(dyActivation, a3D, true, false);\n } else if (transposeA && !transposeB) {\n aDer = unfusedMatMul(b3D, dyActivation, false, true);\n bDer = unfusedMatMul(a3D, dyActivation, false, false);\n } else {\n aDer = unfusedMatMul(b3D, dyActivation, true, true);\n bDer = unfusedMatMul(dyActivation, a3D, true, true);\n }\n\n if (bias != null) {\n const biasDer = getFusedBiasGradient($bias, dyActivation);\n return [aDer, bDer, biasDer];\n } else {\n return [aDer, bDer];\n }\n };\n\n const inputs: _FusedMatMulInputs = {\n a: a3D,\n b: b3D,\n bias: $bias,\n preluActivationWeights: $preluActivationWeights\n };\n const attrs: _FusedMatMulAttrs =\n {transposeA, transposeB, activation, leakyreluAlpha};\n\n // Depending on the the params passed in we will have different number of\n // inputs and thus a a different number of elements in the gradient.\n if (bias == null) {\n const customOp =\n customGrad((a3D: Tensor3D, b3D: Tensor3D, save: GradSaveFunc) => {\n const res =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n _FusedMatMul, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor;\n\n save([a3D, b3D, res]);\n\n return {value: reshape(res, outShape), gradFunc: grad};\n });\n return customOp(a3D, b3D);\n } else {\n const customOpWithBias = customGrad(\n (a3D: Tensor3D, b3D: Tensor3D, $bias: Tensor, save: GradSaveFunc) => {\n const res =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n _FusedMatMul, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor;\n\n save([a3D, b3D, res, $bias]);\n\n return {value: reshape(res, outShape), gradFunc: grad};\n });\n\n return customOpWithBias(a3D, b3D, $bias);\n }\n }\n\n export const matMul = 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 A number to use where the input signal does\n * not exist when padEnd is True.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction frame_(\n signal: Tensor1D, frameLength: number, frameStep: number, padEnd = false,\n padValue = 0): Tensor {\n let start = 0;\n const output: Tensor[] = [];\n while (start + frameLength <= signal.size) {\n output.push(slice(signal, start, frameLength));\n start += frameStep;\n }\n\n if (padEnd) {\n while (start < signal.size) {\n const padLen = (start + frameLength) - signal.size;\n const pad = concat([\n slice(signal, start, frameLength - padLen), fill([padLen], padValue)\n ]);\n output.push(pad);\n start += frameStep;\n }\n }\n\n if (output.length === 0) {\n return tensor2d([], [0, frameLength]);\n }\n\n return reshape(concat(output), [output.length, frameLength]);\n}\nexport const frame = 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 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {tile} from '../tile';\n\n/**\n * Converts images from grayscale to RGB format.\n *\n * @param image A grayscale tensor to convert. The `image`'s last dimension must\n * be size 1 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction grayscaleToRGB_(image: T|TensorLike): T {\n const $image = convertToTensor(image, 'image', 'grayscaleToRGB');\n\n const lastDimsIdx = $image.rank - 1;\n const lastDims = $image.shape[lastDimsIdx];\n\n util.assert(\n $image.rank >= 2,\n () => 'Error in grayscaleToRGB: images must be at least rank 2, ' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n lastDims === 1,\n () => 'Error in grayscaleToRGB: last dimension of a grayscale image ' +\n `should be size 1, but got size ${lastDims}.`);\n\n const reps = new Array($image.rank);\n\n reps.fill(1, 0, lastDimsIdx);\n reps[lastDimsIdx] = 3;\n\n return tile($image, reps);\n}\n\nexport const grayscaleToRGB = op({grayscaleToRGB_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppression_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY): Tensor1D {\n const $boxes =\n convertToTensor(boxes, 'boxes', 'nonMaxSuppression', 'float32');\n const $scores =\n convertToTensor(scores, 'scores', 'nonMaxSuppression', 'float32');\n\n const inputs = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n maxOutputSize = inputs.maxOutputSize;\n iouThreshold = inputs.iouThreshold;\n scoreThreshold = inputs.scoreThreshold;\n\n const attrs = {maxOutputSize, iouThreshold, scoreThreshold};\n return ENGINE.runKernel(\n NonMaxSuppressionV3, {boxes: $boxes, scores: $scores}, attrs);\n}\n\nexport const nonMaxSuppression = op({nonMaxSuppression_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Inserts a value into a sorted array. This method allows duplicate, meaning it\n * allows inserting duplicate value, in which case, the element will be inserted\n * at the lowest index of the value.\n * @param arr The array to modify.\n * @param element The element to insert.\n * @param comparator Optional. If no comparator is specified, elements are\n * compared using array_util.defaultComparator, which is suitable for Strings\n * and Numbers in ascending arrays. If the array contains multiple instances of\n * the target value, the left-most instance will be returned. To provide a\n * comparator, it should take 2 arguments to compare and return a negative,\n * zero, or a positive number.\n */\nexport function binaryInsert(\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(\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(a: T, b: T): number {\n return a > b ? 1 : a < b ? -1 : 0;\n}\n\nfunction binarySearch_(\n arr: T[], target: T, comparator: (a: T, b: T) => number) {\n let left = 0;\n let right = arr.length;\n let middle = 0;\n let found = false;\n while (left < right) {\n middle = left + ((right - left) >>> 1);\n const compareResult = comparator(target, arr[middle]);\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // If compareResult is 0, the value is found. We record it is found,\n // and then keep looking because there may be duplicate.\n found = !compareResult;\n }\n }\n\n return found ? left : -left - 1;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray} from '../types';\nimport {binaryInsert} from './non_max_suppression_util';\n\n/**\n * Implementation of the NonMaxSuppression kernel shared between webgl and cpu.\n */\ninterface Candidate {\n score: number;\n boxIndex: number;\n suppressBeginIndex: number;\n}\n\ninterface NonMaxSuppressionResult {\n selectedIndices: number[];\n selectedScores?: number[];\n validOutputs?: number;\n}\n\nexport function nonMaxSuppressionV3Impl(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number): NonMaxSuppressionResult {\n return nonMaxSuppressionImpl_(\n boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n 0 /* softNmsSigma */);\n}\n\nexport function nonMaxSuppressionV4Impl(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number,\n padToMaxOutputSize: boolean): NonMaxSuppressionResult {\n return nonMaxSuppressionImpl_(\n boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n 0 /* softNmsSigma */, false /* returnScoresTensor */,\n padToMaxOutputSize /* padToMaxOutputSize */, true\n /* returnValidOutputs */);\n}\n\nexport function nonMaxSuppressionV5Impl(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number,\n softNmsSigma: number): NonMaxSuppressionResult {\n return nonMaxSuppressionImpl_(\n boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma,\n true /* returnScoresTensor */);\n}\n\nfunction nonMaxSuppressionImpl_(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number, softNmsSigma: number,\n returnScoresTensor = false, padToMaxOutputSize = false,\n returnValidOutputs = false): NonMaxSuppressionResult {\n // The list is sorted in ascending order, so that we can always pop the\n // candidate with the largest score in O(1) time.\n const candidates = [];\n\n for (let i = 0; i < scores.length; i++) {\n if (scores[i] > scoreThreshold) {\n candidates.push({score: scores[i], boxIndex: i, suppressBeginIndex: 0});\n }\n }\n\n candidates.sort(ascendingComparator);\n\n // If softNmsSigma is 0, the outcome of this algorithm is exactly same as\n // before.\n const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;\n\n const selectedIndices: number[] = [];\n const selectedScores: number[] = [];\n\n while (selectedIndices.length < maxOutputSize && candidates.length > 0) {\n const candidate = candidates.pop();\n const {score: originalScore, boxIndex, suppressBeginIndex} = candidate;\n\n if (originalScore < scoreThreshold) {\n break;\n }\n\n // Overlapping boxes are likely to have similar scores, therefore we\n // iterate through the previously selected boxes backwards in order to\n // see if candidate's score should be suppressed. We use\n // suppressBeginIndex to track and ensure a candidate can be suppressed\n // by a selected box no more than once. Also, if the overlap exceeds\n // iouThreshold, we simply ignore the candidate.\n let ignoreCandidate = false;\n for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {\n const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);\n\n if (iou >= iouThreshold) {\n ignoreCandidate = true;\n break;\n }\n\n candidate.score =\n candidate.score * suppressWeight(iouThreshold, scale, iou);\n\n if (candidate.score <= scoreThreshold) {\n break;\n }\n }\n\n // At this point, if `candidate.score` has not dropped below\n // `scoreThreshold`, then we know that we went through all of the\n // previous selections and can safely update `suppressBeginIndex` to the\n // end of the selected array. Then we can re-insert the candidate with\n // the updated score and suppressBeginIndex back in the candidate list.\n // If on the other hand, `candidate.score` has dropped below the score\n // threshold, we will not add it back to the candidates list.\n candidate.suppressBeginIndex = selectedIndices.length;\n\n if (!ignoreCandidate) {\n // Candidate has passed all the tests, and is not suppressed, so\n // select the candidate.\n if (candidate.score === originalScore) {\n selectedIndices.push(boxIndex);\n selectedScores.push(candidate.score);\n } else if (candidate.score > scoreThreshold) {\n // Candidate's score is suppressed but is still high enough to be\n // considered, so add back to the candidates list.\n binaryInsert(candidates, candidate, ascendingComparator);\n }\n }\n }\n\n // NonMaxSuppressionV4 feature: padding output to maxOutputSize.\n const validOutputs = selectedIndices.length;\n const elemsToPad = maxOutputSize - validOutputs;\n\n if (padToMaxOutputSize && elemsToPad > 0) {\n selectedIndices.push(...new Array(elemsToPad).fill(0));\n selectedScores.push(...new Array(elemsToPad).fill(0.0));\n }\n\n const result: NonMaxSuppressionResult = {selectedIndices};\n\n if (returnScoresTensor) {\n result['selectedScores'] = selectedScores;\n }\n\n if (returnValidOutputs) {\n result['validOutputs'] = validOutputs;\n }\n\n return result;\n}\n\nfunction intersectionOverUnion(boxes: TypedArray, i: number, j: number) {\n const iCoord = boxes.subarray(i * 4, i * 4 + 4);\n const jCoord = boxes.subarray(j * 4, j * 4 + 4);\n const yminI = Math.min(iCoord[0], iCoord[2]);\n const xminI = Math.min(iCoord[1], iCoord[3]);\n const ymaxI = Math.max(iCoord[0], iCoord[2]);\n const xmaxI = Math.max(iCoord[1], iCoord[3]);\n const yminJ = Math.min(jCoord[0], jCoord[2]);\n const xminJ = Math.min(jCoord[1], jCoord[3]);\n const ymaxJ = Math.max(jCoord[0], jCoord[2]);\n const xmaxJ = Math.max(jCoord[1], jCoord[3]);\n const areaI = (ymaxI - yminI) * (xmaxI - xminI);\n const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);\n if (areaI <= 0 || areaJ <= 0) {\n return 0.0;\n }\n const intersectionYmin = Math.max(yminI, yminJ);\n const intersectionXmin = Math.max(xminI, xminJ);\n const intersectionYmax = Math.min(ymaxI, ymaxJ);\n const intersectionXmax = Math.min(xmaxI, xmaxJ);\n const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *\n Math.max(intersectionXmax - intersectionXmin, 0.0);\n return intersectionArea / (areaI + areaJ - intersectionArea);\n}\n\n// A Gaussian penalty function, this method always returns values in [0, 1].\n// The weight is a function of similarity, the more overlap two boxes are, the\n// smaller the weight is, meaning highly overlapping boxe will be significantly\n// penalized. On the other hand, a non-overlapping box will not be penalized.\nfunction suppressWeight(iouThreshold: number, scale: number, iou: number) {\n const weight = Math.exp(scale * iou * iou);\n return iou <= iouThreshold ? weight : 0.0;\n}\n\nfunction ascendingComparator(c1: Candidate, c2: Candidate) {\n // For objects with same scores, we make the object with the larger index go\n // first. In an array that pops from the end, this means that the object with\n // the smaller index will be popped first. This ensures the same output as\n // the TensorFlow python version.\n return (c1.score - c2.score) ||\n ((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {nonMaxSuppressionV3Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This is the async version of `nonMaxSuppression`\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionAsync_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY): Promise {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n const inputs = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n maxOutputSize = inputs.maxOutputSize;\n iouThreshold = inputs.iouThreshold;\n scoreThreshold = inputs.scoreThreshold;\n\n const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n const boxesVals = boxesAndScores[0];\n const scoresVals = boxesAndScores[1];\n\n // We call a cpu based impl directly with the typedarray data here rather\n // than a kernel because all kernels are synchronous (and thus cannot await\n // .data()).\n const {selectedIndices} = nonMaxSuppressionV3Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n if ($boxes !== boxes) {\n $boxes.dispose();\n }\n if ($scores !== scores) {\n $scores.dispose();\n }\n\n return tensor1d(selectedIndices, 'int32');\n}\n\nexport const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n * When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - selectedScores: A 1D tensor with the corresponding scores for each\n * selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionWithScore_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n softNmsSigma = 0.0): NamedTensorMap {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n maxOutputSize = params.maxOutputSize;\n iouThreshold = params.iouThreshold;\n scoreThreshold = params.scoreThreshold;\n softNmsSigma = params.softNmsSigma;\n\n const inputs: NonMaxSuppressionV5Inputs = {boxes: $boxes, scores: $scores};\n const attrs: NonMaxSuppressionV5Attrs =\n {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const result = ENGINE.runKernel(\n NonMaxSuppressionV5, inputs as {} 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 (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n * When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - selectedScores: A 1D tensor with the corresponding scores for each\n * selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionWithScoreAsync_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n softNmsSigma = 0.0): Promise {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n maxOutputSize = params.maxOutputSize;\n iouThreshold = params.iouThreshold;\n scoreThreshold = params.scoreThreshold;\n softNmsSigma = params.softNmsSigma;\n\n const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n const boxesVals = boxesAndScores[0];\n const scoresVals = boxesAndScores[1];\n\n // We call a cpu based impl directly with the typedarray data here rather\n // than a kernel because all kernels are synchronous (and thus cannot await\n // .data()).\n const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n\n if ($boxes !== boxes) {\n $boxes.dispose();\n }\n if ($scores !== scores) {\n $scores.dispose();\n }\n\n return {\n selectedIndices: tensor1d(selectedIndices, 'int32'),\n selectedScores: tensor1d(selectedScores)\n };\n}\n\nexport const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n * `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - validOutputs: A scalar denoting how many elements in `selectedIndices`\n * are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionPadded_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n padToMaxOutputSize = false): NamedTensorMap {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n null /* softNmsSigma */);\n const $maxOutputSize = params.maxOutputSize;\n const $iouThreshold = params.iouThreshold;\n const $scoreThreshold = params.scoreThreshold;\n\n const inputs: NonMaxSuppressionV4Inputs = {boxes: $boxes, scores: $scores};\n const attrs: NonMaxSuppressionV4Attrs = {\n maxOutputSize: $maxOutputSize,\n iouThreshold: $iouThreshold,\n scoreThreshold: $scoreThreshold,\n padToMaxOutputSize\n };\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const result = ENGINE.runKernel(\n NonMaxSuppressionV4, inputs as {} 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 Defaults to false. If true, size of output\n * `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - validOutputs: A scalar denoting how many elements in `selectedIndices`\n * are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionPaddedAsync_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n padToMaxOutputSize = false): Promise {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n null /* softNmsSigma */);\n const $maxOutputSize = params.maxOutputSize;\n const $iouThreshold = params.iouThreshold;\n const $scoreThreshold = params.scoreThreshold;\n\n const [boxesVals, scoresVals] =\n await Promise.all([$boxes.data(), $scores.data()]);\n\n // We call a cpu based impl directly with the typedarray data here rather\n // than a kernel because all kernels are synchronous (and thus cannot await\n // .data()).\n const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold,\n padToMaxOutputSize);\n\n if ($boxes !== boxes) {\n $boxes.dispose();\n }\n if ($scores !== scores) {\n $scores.dispose();\n }\n\n return {\n selectedIndices: tensor1d(selectedIndices, 'int32'),\n validOutputs: scalar(validOutputs, 'int32')\n };\n}\n\nexport const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Bilinear resize a single 3D image or a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n * images to. Each channel is resized individually.\n * @param alignCorners Defaults to `false`. If true, rescale\n * input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n * corners of images and resized images. If false, rescale by\n * `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers\n * are at 0.5, which would make the floating point coordinates of the top\n * left pixel 0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeBilinear_(\n images: T|TensorLike, size: [number, number], alignCorners = false,\n halfPixelCenters = false): T {\n const $images = convertToTensor(images, 'images', 'resizeBilinear');\n\n util.assert(\n $images.rank === 3 || $images.rank === 4,\n () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +\n `rank ${$images.rank}.`);\n util.assert(\n size.length === 2,\n () => `Error in resizeBilinear: new shape must 2D, but got shape ` +\n `${size}.`);\n util.assert(\n halfPixelCenters === false || alignCorners === false,\n () => `Error in resizeBilinear: If halfPixelCenters is true, ` +\n `alignCorners must be false.`);\n\n let batchImages = $images as Tensor4D;\n let reshapedTo4D = false;\n if ($images.rank === 3) {\n reshapedTo4D = true;\n batchImages = reshape(\n $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n }\n\n const [] = size;\n\n const inputs: ResizeBilinearInputs = {images: batchImages};\n const attrs: ResizeBilinearAttrs = {alignCorners, halfPixelCenters, size};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n ResizeBilinear, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const resizeBilinear = op({resizeBilinear_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * NearestNeighbor resize a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n * images to. Each channel is resized individually.\n * @param alignCorners Defaults to False. If true, rescale\n * input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n * corners of images and resized images. If false, rescale by\n * `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixels are of\n * half the actual dimensions, and yield more accurate resizes. This flag\n * would also make the floating point coordinates of the top left pixel\n * 0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeNearestNeighbor_(\n images: T|TensorLike, size: [number, number], alignCorners = false,\n halfPixelCenters = false): T {\n const $images = convertToTensor(images, 'images', 'resizeNearestNeighbor');\n\n util.assert(\n $images.rank === 3 || $images.rank === 4,\n () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +\n `rank ${$images.rank}.`);\n util.assert(\n size.length === 2,\n () =>\n `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +\n `${size}.`);\n util.assert(\n $images.dtype === 'float32' || $images.dtype === 'int32',\n () => '`images` must have `int32` or `float32` as dtype');\n util.assert(\n halfPixelCenters === false || alignCorners === false,\n () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +\n `alignCorners must be false.`);\n let batchImages = $images as Tensor4D;\n let reshapedTo4D = false;\n if ($images.rank === 3) {\n reshapedTo4D = true;\n batchImages = reshape(\n $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n }\n const [] = size;\n\n const inputs: ResizeNearestNeighborInputs = {images: batchImages};\n const attrs:\n ResizeNearestNeighborAttrs = {alignCorners, halfPixelCenters, size};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n ResizeNearestNeighbor, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const resizeNearestNeighbor = op({resizeNearestNeighbor_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { Tensor1D, Tensor3D } from '../../tensor';\nimport { tensor1d } from '../tensor1d';\nimport { TensorLike } from '../../types';\nimport { op } from '../operation';\nimport { cast } from '../cast';\nimport { split } from '../split';\nimport { bincount } from '../bincount';\nimport { lessEqual } from '../less_equal';\nimport { greater } from '../greater';\nimport { sum } from '../sum';\nimport { add } from '../add';\nimport { mul } from '../mul';\nimport { div } from '../div';\nimport { sub } from '../sub';\nimport { round } from '../round';\nimport { where } from '../where';\nimport { fill } from '../fill';\nimport {slice} from '../slice';\nimport { range } from '../range';\nimport { tensor } from '../tensor';\nimport * as util from '../../util';\nimport { convertToTensor } from '../../tensor_util_env';\n\n/**\n * Performs image binarization with corresponding threshold\n * (depends on the method)value, which creates a binary image from a grayscale.\n * @param image 3d tensor of shape [imageHeight,imageWidth, depth],\n * where imageHeight and imageWidth must be positive.The image color\n * range should be [0, 255].\n * @param method Optional string from `'binary' | 'otsu'`\n * which specifies the method for thresholding. Defaults to 'binary'.\n * @param inverted Optional boolean whichspecifies\n * if colours should be inverted. Defaults to false.\n * @param threshValue Optional number which defines threshold value from 0 to 1.\n * Defaults to 0.5.\n * @return A 3d tensor of shape [imageHeight,imageWidth, depth], which\n * contains binarized image.\n */\n\nfunction threshold_(\n image: Tensor3D | TensorLike,\n method = 'binary',\n inverted = false,\n threshValue = 0.5\n): Tensor3D {\n const $image = convertToTensor(image, 'image', 'threshold');\n\n /* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.\n\tReference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29 */\n\n const RED_INTENCITY_COEF = 0.2989;\n const GREEN_INTENCITY_COEF = 0.5870;\n const BLUE_INTENCITY_COEF = 0.1140;\n const totalPixelsInImage = $image.shape[0] * $image.shape[1];\n\n let $threshold = mul(tensor1d([threshValue]), 255);\n let r, g, b, grayscale;\n\n util.assert(\n $image.rank === 3,\n () => 'Error in threshold: image must be rank 3,' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n $image.shape[2] === 3 || $image.shape[2]=== 1,\n () => 'Error in threshold: ' +\n 'image color channel must be equal to 3 or 1' +\n `but got ${$image.shape[2]}.`);\n\n util.assert(\n $image.dtype === 'int32' || $image.dtype === 'float32',\n () => 'Error in dtype: image dtype must be int32 or float32,' +\n `but got dtype ${$image.dtype}.`);\n\n util.assert(\n method === 'otsu' || method === 'binary',\n () => `Method must be binary or otsu, but was ${method}`);\n\n if ($image.shape[2] === 3) {\n [r, g, b] = split($image, [1, 1, 1], -1);\n const $r = mul(r,RED_INTENCITY_COEF);\n const $g = mul(g,GREEN_INTENCITY_COEF);\n const $b = mul(b,BLUE_INTENCITY_COEF);\n grayscale = add(add($r, $g), $b);\n } else {\n grayscale = image;\n }\n\n if (method === 'otsu') {\n const $histogram = bincount(cast(round(grayscale), 'int32') as Tensor1D,\n tensor([]),\n 256);\n $threshold = otsu($histogram, totalPixelsInImage);\n }\n\n const invCondition = inverted ?\n lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);\n\n const result = cast(mul(invCondition,255), 'int32');\n\n return result as Tensor3D;\n}\n\nfunction otsu(histogram: Tensor1D, total: number):Tensor1D {\n\n let bestThresh = tensor1d([-1]);\n let bestInBetVar = tensor1d([0]);\n let cInBetVar = tensor1d([0]);\n let classFirst, classSecond, meanFirst,\n meanSec, weightForeground, weightBack;\n\n for (let index = 0; index < histogram.size-1; index++) {\n\n classFirst = slice(histogram, 0, index + 1);\n\n classSecond = slice(histogram,index + 1);\n\n weightForeground = div(sum(classFirst),total);\n\n weightBack = div(sum(classSecond),total);\n\n const meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));\n\n meanFirst = div(meanFirstDivA, sum(classFirst) );\n\n const meanSecFill = fill(classSecond.shape, classFirst.size);\n const meanSecAdd = add(range(0,classSecond.size),meanSecFill);\n const meanSecMul = mul(classSecond, (meanSecAdd));\n meanSec = div(sum(meanSecMul), sum(classSecond));\n\n const cInBetVarSubA = sub(meanFirst, meanSec);\n const cInBetVarSubB = sub(meanFirst, meanSec);\n const cInBetVarMul = mul(weightForeground, weightBack);\n cInBetVar = mul(mul(cInBetVarMul,cInBetVarSubA), cInBetVarSubB);\n\n const condition = greater(cInBetVar, bestInBetVar);\n\n bestInBetVar = where(condition, cInBetVar, bestInBetVar);\n\n bestThresh = where(condition, tensor1d([index]), bestThresh);\n\n }\n return bestThresh;\n}\n\nexport const threshold = op({ threshold_ });\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {Transform, TransformAttrs, TransformInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Applies the given transform(s) to the image(s).\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param transforms Projective transform matrix/matrices. A tensor1d of length\n * 8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0,\n * b1, b2, c0, c1], then it maps the output point (x, y) to a transformed\n * input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),\n * where k = c0 x + c1 y + 1. The transforms are inverted compared to the\n * transform mapping input points to output points.\n * @param interpolation Interpolation mode.\n * Supported values: 'nearest', 'bilinear'. Default to 'nearest'.\n * @param fillMode Points outside the boundaries of the input are filled\n * according to the given mode, one of 'constant', 'reflect', 'wrap',\n * 'nearest'. Default to 'constant'.\n * 'reflect': (d c b a | a b c d | d c b a ) The input is extended by\n * reflecting about the edge of the last pixel.\n * 'constant': (k k k k | a b c d | k k k k) The input is extended by\n * filling all values beyond the edge with the same constant value k.\n * 'wrap': (a b c d | a b c d | a b c d) The input is extended by\n * wrapping around to the opposite edge.\n * 'nearest': (a a a a | a b c d | d d d d) The input is extended by\n * the nearest pixel.\n * @param fillValue A float represents the value to be filled outside the\n * boundaries when fillMode is 'constant'.\n * @param Output dimension after the transform, [height, width]. If undefined,\n * output is the same size as input image.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction transform_(\n image: Tensor4D|TensorLike, transforms: Tensor2D|TensorLike,\n interpolation: 'nearest'|'bilinear' = 'nearest',\n fillMode: 'constant'|'reflect'|'wrap'|'nearest' = 'constant', fillValue = 0,\n outputShape?: [number, number]): Tensor4D {\n const $image = convertToTensor(image, 'image', 'transform', 'float32');\n const $transforms =\n convertToTensor(transforms, 'transforms', 'transform', 'float32');\n\n util.assert(\n $image.rank === 4,\n () => 'Error in transform: image must be rank 4,' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n $transforms.rank === 2 &&\n ($transforms.shape[0] === $image.shape[0] ||\n $transforms.shape[0] === 1) &&\n $transforms.shape[1] === 8,\n () => `Error in transform: Input transform should be batch x 8 or 1 x 8`);\n\n util.assert(\n outputShape == null || outputShape.length === 2,\n () =>\n 'Error in transform: outputShape must be [height, width] or null, ' +\n `but got ${outputShape}.`);\n\n const inputs: TransformInputs = {image: $image, transforms: $transforms};\n const attrs:\n TransformAttrs = {interpolation, fillMode, fillValue, outputShape};\n\n return ENGINE.runKernel(\n Transform, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const transform = op({transform_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assert} from '../../util';\n\nimport {greaterEqual} from '../greater_equal';\nimport {lessEqual} from '../less_equal';\nimport {logicalAnd} from '../logical_and';\nimport {op} from '../operation';\nimport {range} from '../range';\nimport {reshape} from '../reshape';\nimport {scalar} from '../scalar';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\nimport {zeros} from '../zeros';\n\n/**\n * Copy a tensor setting everything outside a central band in each innermost\n * matrix to zero.\n *\n * The band part is computed as follows: Assume input has `k` dimensions\n * `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where\n * `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.\n * The indicator function\n * `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)`\n * `&& (num_upper < 0 || (n-m) <= num_upper)`\n *\n * ```js\n * const x = tf.tensor2d([[ 0, 1, 2, 3],\n * [-1, 0, 1, 2],\n * [-2, -1, 0, 1],\n * [-3, -2, -1, 0]]);\n * let y = tf.linalg.bandPart(x, 1, -1);\n * y.print(); // [[ 0, 1, 2, 3],\n * // [-1, 0, 1, 2],\n * // [ 0, -1, 0, 1],\n * // [ 0, 0 , -1, 0]]\n * let z = tf.linalg.bandPart(x, 2, 1);\n * z.print(); // [[ 0, 1, 0, 0],\n * // [-1, 0, 1, 0],\n * // [-2, -1, 0, 1],\n * // [ 0, -2, -1, 0]]\n * ```\n *\n * @param x Rank `k` tensor\n * @param numLower Number of subdiagonals to keep.\n * If negative, keep entire lower triangle.\n * @param numUpper Number of subdiagonals to keep.\n * If negative, keep entire upper triangle.\n * @returns Rank `k` tensor of the same shape as input.\n * The extracted banded tensor.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction bandPart_(\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('Orthogonalized:');\n * y.dot(y.transpose()).print(); // should be nearly the identity matrix.\n * console.log('First row direction maintained:');\n * const data = await y.array();\n * console.log(data[0][1] / data[0][0]); // should be nearly 2.\n * ```\n *\n * @param xs The vectors to be orthogonalized, in one of the two following\n * formats:\n * - An Array of `tf.Tensor1D`.\n * - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows\n * of `xs`.\n * In each case, all the vectors must have the same length and the length\n * must be greater than or equal to the number of vectors.\n * @returns The orthogonalized and normalized vectors or matrix.\n * Orthogonalization means that the vectors or the rows of the matrix\n * are orthogonal (zero inner products). Normalization means that each\n * vector or each row of the matrix has an L2 norm that equals `1`.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction gramSchmidt_(xs: Tensor1D[]|Tensor2D): Tensor1D[]|Tensor2D {\n let inputIsTensor2D: boolean;\n if (Array.isArray(xs)) {\n inputIsTensor2D = false;\n assert(\n xs != null && xs.length > 0,\n () => 'Gram-Schmidt process: input must not be null, undefined, or ' +\n 'empty');\n const dim = xs[0].shape[0];\n for (let i = 1; i < xs.length; ++i) {\n assert(\n xs[i].shape[0] === dim,\n () =>\n 'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +\n `(${(xs as Tensor1D[])[i].shape[0]} vs. ${dim})`);\n }\n } else {\n inputIsTensor2D = true;\n xs = split(xs, xs.shape[0], 0).map(x => squeeze(x, [0]));\n }\n\n assert(\n xs.length <= xs[0].shape[0],\n () => `Gram-Schmidt: Number of vectors (${\n (xs as Tensor1D[]).length}) exceeds ` +\n `number of dimensions (${(xs as Tensor1D[])[0].shape[0]}).`);\n\n const ys: Tensor1D[] = [];\n const xs1d = xs;\n for (let i = 0; i < xs.length; ++i) {\n ys.push(ENGINE.tidy(() => {\n let x = xs1d[i];\n if (i > 0) {\n for (let j = 0; j < i; ++j) {\n const proj = mul(sum(mul(ys[j], x)), ys[j]);\n x = sub(x, proj);\n }\n }\n return div(x, norm(x, 'euclidean'));\n }));\n }\n\n if (inputIsTensor2D) {\n return stack(ys, 0) as Tensor2D;\n } else {\n return ys;\n }\n}\n\nexport const gramSchmidt = op({gramSchmidt_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {dispose} from '../../globals';\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {clone} from '../clone';\nimport {concat} from '../concat';\nimport {div} from '../div';\nimport {eye} from '../eye';\nimport {greater} from '../greater';\nimport {matMul} from '../mat_mul';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {tensor2d} from '../tensor2d';\nimport {transpose} from '../transpose';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\n\n/**\n * Compute QR decomposition of m-by-n matrix using Householder transformation.\n *\n * Implementation based on\n * [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]\n * (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [3, 4]]);\n * let [q, r] = tf.linalg.qr(a);\n * console.log('Q');\n * q.print();\n * console.log('R');\n * r.print();\n * console.log('Orthogonalized');\n * q.dot(q.transpose()).print() // should be nearly the identity matrix.\n * console.log('Reconstructed');\n * q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];\n * ```\n *\n * @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose\n * it has the shape `[..., M, N]`.\n * @param fullMatrices An optional boolean parameter. Defaults to `false`.\n * If `true`, compute full-sized `Q`. If `false` (the default),\n * compute only the leading N columns of `Q` and `R`.\n * @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,\n * i.e., its columns all have unit norm and are mutually orthogonal.\n * If `M >= N`,\n * If `fullMatrices` is `false` (default),\n * - `Q` has a shape of `[..., M, N]`,\n * - `R` has a shape of `[..., N, N]`.\n * If `fullMatrices` is `true` (default),\n * - `Q` has a shape of `[..., M, M]`,\n * - `R` has a shape of `[..., M, N]`.\n * If `M < N`,\n * - `Q` has a shape of `[..., M, M]`,\n * - `R` has a shape of `[..., M, N]`.\n * @throws If the rank of `x` is less than 2.\n *\n * @doc {heading:'Operations',\n * subheading:'Linear Algebra',\n * namespace:'linalg'}\n */\nfunction qr_(x: Tensor, fullMatrices = false): [Tensor, Tensor] {\n assert(\n x.rank >= 2,\n () => `qr() requires input tensor to have a rank >= 2, but got rank ${\n x.rank}`);\n\n if (x.rank === 2) {\n return qr2d(x as Tensor2D, fullMatrices);\n } else {\n // Rank > 2.\n // TODO(cais): Below we split the input into individual 2D tensors,\n // perform QR decomposition on them and then stack the results back\n // together. We should explore whether this can be parallelized.\n const outerDimsProd = x.shape.slice(0, x.shape.length - 2)\n .reduce((value, prev) => value * prev);\n const x2ds = unstack(\n reshape(\n x,\n [\n outerDimsProd, x.shape[x.shape.length - 2],\n x.shape[x.shape.length - 1]\n ]),\n 0);\n const q2ds: Tensor2D[] = [];\n const r2ds: Tensor2D[] = [];\n x2ds.forEach(x2d => {\n const [q2d, r2d] = qr2d(x2d as Tensor2D, fullMatrices);\n q2ds.push(q2d);\n r2ds.push(r2d);\n });\n const q = reshape(stack(q2ds, 0), x.shape);\n const r = reshape(stack(r2ds, 0), x.shape);\n return [q, r];\n }\n}\n\nfunction qr2d(x: Tensor2D, fullMatrices = false): [Tensor2D, Tensor2D] {\n return ENGINE.tidy(() => {\n assert(\n x.shape.length === 2,\n () => `qr2d() requires a 2D Tensor, but got a ${\n x.shape.length}D Tensor.`);\n\n const m = x.shape[0];\n const n = x.shape[1];\n\n let q = eye(m); // Orthogonal transform so far.\n let r = clone(x); // Transformed matrix so far.\n\n const one2D = tensor2d([[1]], [1, 1]);\n let w: Tensor2D = clone(one2D);\n\n const iters = m >= n ? n : m;\n for (let j = 0; j < iters; ++j) {\n // This tidy within the for-loop ensures we clean up temporary\n // tensors as soon as they are no longer needed.\n const rTemp = r;\n const wTemp = w;\n const qTemp = q;\n [w, r, q] = ENGINE.tidy((): [Tensor2D, Tensor2D, Tensor2D] => {\n // Find H = I - tau * w * w', to put zeros below R(j, j).\n const rjEnd1 = slice(r, [j, j], [m - j, 1]);\n const normX = norm(rjEnd1);\n const rjj = slice(r, [j, j], [1, 1]);\n\n // The sign() function returns 0 on 0, which causes division by zero.\n const s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));\n\n const u1 = sub(rjj, mul(s, normX));\n const wPre = div(rjEnd1, u1);\n if (wPre.shape[0] === 1) {\n w = clone(one2D);\n } else {\n w = concat(\n [\n one2D,\n slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]]) as\n Tensor2D\n ],\n 0);\n }\n const tau = neg(div(matMul(s, u1), normX)) as Tensor2D;\n\n // -- R := HR, Q := QH.\n const rjEndAll = slice(r, [j, 0], [m - j, n]);\n const tauTimesW: Tensor2D = mul(tau, w);\n const wT: Tensor2D = transpose(w);\n if (j === 0) {\n r = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n } else {\n const rTimesTau: Tensor2D =\n sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n r = concat([slice(r, [0, 0], [j, n]), rTimesTau], 0);\n }\n const tawTimesWT: Tensor2D = transpose(tauTimesW);\n const qAllJEnd = slice(q, [0, j], [m, q.shape[1] - j]);\n if (j === 0) {\n q = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n } else {\n const qTimesTau: Tensor2D =\n sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n q = concat([slice(q, [0, 0], [m, j]), qTimesTau], 1);\n }\n return [w, r, q];\n });\n dispose([rTemp, wTemp, qTemp]);\n }\n\n if (!fullMatrices && m > n) {\n q = slice(q, [0, 0], [m, n]);\n r = slice(r, [0, 0], [n, n]);\n }\n\n return [q, r];\n }) as [Tensor2D, Tensor2D];\n}\n\nexport const qr = op({qr_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport enum Reduction {\n NONE,\n MEAN,\n SUM,\n SUM_BY_NONZERO_WEIGHTS\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {Reduction} from '../loss_ops_utils';\nimport {mean} from '../mean';\nimport {mul} from '../mul';\nimport {notEqual} from '../not_equal';\nimport {ones} from '../ones';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sum} from '../sum';\n\n/**\n * Computes the weighted loss between two tensors.\n *\n * @param losses Tensor of shape `[batch_size, d1, ..., dN]`.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `losses`, and must be broadcastable to `losses` (i.e., all\n * dimensions must be either `1`, or the same as the corresponding\n * `losses` dimension).\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction computeWeightedLoss_(\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_(\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_(\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_(\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_(\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_(\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_(\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_(\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_(\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_(\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_(\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 =\n convertToTensor(indices, 'indices', 'sparseFillEmptyRows', 'int32');\n const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');\n const $denseShape =\n convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows', 'int32');\n const $defaultValue = convertToTensor(\n defaultValue, 'defaultValue', 'sparseFillEmptyRows', $values.dtype);\n\n if ($indices.rank !== 2) {\n throw new Error(`Indices should be Tensor2D but received shape\n ${$indices.shape}`);\n }\n if ($values.rank !== 1) {\n throw new Error(\n `Values should be Tensor1D but received shape ${$values.shape}`);\n }\n if ($denseShape.rank !== 1) {\n throw new Error(`Dense shape should be Tensor1D but received shape ${\n $denseShape.shape}`);\n }\n if ($defaultValue.rank !== 0) {\n throw new Error(`Default value should be a scalar but received shape ${\n $defaultValue.shape}`);\n }\n\n const inputs: SparseFillEmptyRowsInputs = {\n indices: $indices,\n values: $values,\n denseShape: $denseShape,\n defaultValue: $defaultValue\n };\n\n const result: Tensor[] = ENGINE.runKernel(SparseFillEmptyRows, inputs as {});\n return {\n outputIndices: result[0],\n outputValues: result[1],\n emptyRowIndicator: result[2],\n reverseIndexMap: result[3]\n };\n}\n\nexport const sparseFillEmptyRows = op({sparseFillEmptyRows_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseReshape, SparseReshapeInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * This operation has the same semantics as reshape on the represented dense\n * tensor. The `inputIndices` are recomputed based on the requested `newShape`.\n * If one component of `newShape` is the special value -1, the size of that\n * dimension is computed so that the total dense size remains constant. At most\n * one component of `newShape` can be -1. The number of dense elements implied\n * by `newShape` must be the same as the number of dense elements originally\n * implied by `inputShape`. Reshaping does not affect the order of values in the\n * SparseTensor. If the input tensor has rank R_in and N non-empty values, and\n * `newShape` has length R_out, then `inputIndices` has shape [N, R_in],\n * `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and\n * `outputShape` has length R_out.\n *\n * ```js\n * const result = tf.sparse.sparseReshape(\n * [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],\n * [2, 3, 6], [9, -1]);\n * console.log(result);\n * result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]\n * result['outputShape'].print(); // [9, 4]\n * ```\n * @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty\n * values in a SparseTensor.\n * @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense\n * shape.\n * @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.\n * @return A map with the following properties:\n * - outputIndices: 2-D. N x R_out matrix with the updated indices of\n * non-empty values in the output SparseTensor.\n * - outputShape: 1-D. R_out vector with the full dense shape of the output\n * SparseTensor. This is the same as newShape but with any -1 dimensions\n * filled in.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseReshape_(\n inputIndices: Tensor2D|TensorLike, inputShape: Tensor1D|TensorLike,\n newShape: Tensor1D|TensorLike): NamedTensorMap {\n const $inputIndices =\n convertToTensor(inputIndices, 'inputIndices', 'sparseReshape', 'int32');\n const $inputShape =\n convertToTensor(inputShape, 'inputShape', 'sparseReshape', 'int32');\n const $newShape =\n convertToTensor(newShape, 'newShape', 'sparseReshape', 'int32');\n\n if ($inputIndices.rank !== 2) {\n throw new Error(`Input indices should be Tensor2D but received shape\n ${$inputIndices.shape}`);\n }\n if ($inputShape.rank !== 1) {\n throw new Error(`Input shape should be Tensor1D but received shape ${\n $inputShape.shape}`);\n }\n if ($newShape.rank !== 1) {\n throw new Error(\n `New shape should be Tensor1D but received shape ${$newShape.shape}`);\n }\n\n const inputs: SparseReshapeInputs = {\n inputIndices: $inputIndices,\n inputShape: $inputShape,\n newShape: $newShape\n };\n const result: Tensor[] = ENGINE.runKernel(SparseReshape, inputs as {});\n return {outputIndices: result[0], outputShape: result[1]};\n}\n\nexport const sparseReshape = op({sparseReshape_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentMean, SparseSegmentMeanInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the mean along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [6,7,8,9]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentMean(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentMean(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentMean(c,\n * tf.tensor1d([0, 1, 2], 'int32'),\n * tf.tensor1d([0, 1, 1], 'int32'));\n * result3.print(); // [[1.0, 2.0, 3.0, 4.0], [2.5, 2.5, 2.5, 2.5]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n * assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n * segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n * should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n * the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentMean_(\n data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n segmentIds: Tensor1D|TensorLike): Tensor {\n const $data = convertToTensor(data, 'data', 'sparseSegmentMean');\n const $indices =\n convertToTensor(indices, 'indices', 'sparseSegmentMean', 'int32');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentMean', 'int32');\n\n if ($data.rank < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if ($indices.rank !== 1) {\n throw new Error(`Indices should be Tensor1D but received shape\n ${$indices.shape}`);\n }\n if ($segmentIds.rank !== 1) {\n throw new Error(`Segment ids should be Tensor1D but received shape\n ${$segmentIds.shape}`);\n }\n\n const inputs: SparseSegmentMeanInputs = {\n data: $data,\n indices: $indices,\n segmentIds: $segmentIds\n };\n\n return ENGINE.runKernel(SparseSegmentMean, inputs as {});\n}\n\nexport const sparseSegmentMean = op({sparseSegmentMean_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentSum, SparseSegmentSumInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the sum along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentSum(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentSum(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentSum(c,\n * tf.tensor1d([0, 1, 2], 'int32'),\n * tf.tensor1d([0, 0, 1], 'int32'));\n * result3.print(); // [[0, 0, 0, 0], [5, 6, 7, 8]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n * assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n * segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n * should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n * the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentSum_(\n data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n segmentIds: Tensor1D|TensorLike): Tensor {\n const $data = convertToTensor(data, 'data', 'sparseSegmentSum');\n const $indices =\n convertToTensor(indices, 'indices', 'sparseSegmentSum', 'int32');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentSum', 'int32');\n\n if ($data.rank < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if ($indices.rank !== 1) {\n throw new Error(`Indices should be Tensor1D but received shape\n ${$indices.shape}`);\n }\n if ($segmentIds.rank !== 1) {\n throw new Error(`Segment ids should be Tensor1D but received shape\n ${$segmentIds.shape}`);\n }\n\n const inputs: SparseSegmentSumInputs = {\n data: $data,\n indices: $indices,\n segmentIds: $segmentIds\n };\n\n return ENGINE.runKernel(SparseSegmentSum, inputs as {});\n}\n\nexport const sparseSegmentSum = 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 {broadcastArgs} from './broadcast_args';\nexport {broadcastTo} from './broadcast_to';\nexport {buffer} from './buffer';\nexport {cast} from './cast';\nexport {ceil} from './ceil';\nexport {clipByValue} from './clip_by_value';\nexport {clone} from './clone';\nexport {complex} from './complex';\nexport {concat} from './concat';\nexport {concat1d} from './concat_1d';\nexport {concat2d} from './concat_2d';\nexport {concat3d} from './concat_3d';\nexport {concat4d} from './concat_4d';\nexport {conv1d} from './conv1d';\nexport {conv2d} from './conv2d';\nexport {conv2dTranspose} from './conv2d_transpose';\nexport {conv3d} from './conv3d';\nexport {conv3dTranspose} from './conv3d_transpose';\nexport {cos} from './cos';\nexport {cosh} from './cosh';\nexport {cumprod} from './cumprod';\nexport {cumsum} from './cumsum';\nexport {denseBincount} from './dense_bincount';\nexport {depthToSpace} from './depth_to_space';\nexport {depthwiseConv2d} from './depthwise_conv2d';\nexport {diag} from './diag';\nexport {dilation2d} from './dilation2d';\nexport {div} from './div';\nexport {divNoNan} from './div_no_nan';\nexport {dot} from './dot';\nexport {einsum} from './einsum';\nexport {elu} from './elu';\nexport {equal} from './equal';\nexport {erf} from './erf';\nexport {euclideanNorm} from './euclidean_norm';\nexport {exp} from './exp';\nexport {expandDims} from './expand_dims';\nexport {expm1} from './expm1';\nexport {eye} from './eye';\nexport {fill} from './fill';\nexport {floor} from './floor';\nexport {floorDiv} from './floorDiv';\nexport {gather} from './gather';\nexport {greater} from './greater';\nexport {greaterEqual} from './greater_equal';\nexport {imag} from './imag';\nexport {isFinite} from './is_finite';\nexport {isInf} from './is_inf';\nexport {isNaN} from './is_nan';\nexport {leakyRelu} from './leaky_relu';\nexport {less} from './less';\nexport {lessEqual} from './less_equal';\nexport {linspace} from './linspace';\nexport {localResponseNormalization} from './local_response_normalization';\nexport {log} from './log';\nexport {log1p} from './log1p';\nexport {logSigmoid} from './log_sigmoid';\nexport {logSoftmax} from './log_softmax';\nexport {logSumExp} from './log_sum_exp';\nexport {logicalAnd} from './logical_and';\nexport {logicalNot} from './logical_not';\nexport {logicalOr} from './logical_or';\nexport {logicalXor} from './logical_xor';\nexport {lowerBound} from './lower_bound';\nexport {matMul} from './mat_mul';\nexport {max} from './max';\nexport {maxPool} from './max_pool';\nexport {maxPool3d} from './max_pool_3d';\nexport {maxPoolWithArgmax} from './max_pool_with_argmax';\nexport {maximum} from './maximum';\nexport {mean} from './mean';\nexport {meshgrid} from './meshgrid';\nexport {min} from './min';\nexport {minimum} from './minimum';\nexport {mirrorPad} from './mirror_pad';\nexport {mod} from './mod';\nexport {moments} from './moments';\nexport {mul} from './mul';\nexport {LSTMCellFunc, multiRNNCell} from './multi_rnn_cell';\nexport {multinomial} from './multinomial';\nexport {neg} from './neg';\nexport {notEqual} from './not_equal';\nexport {oneHot} from './one_hot';\nexport {ones} from './ones';\nexport {onesLike} from './ones_like';\nexport {outerProduct} from './outer_product';\nexport {pad} from './pad';\nexport {pad1d} from './pad1d';\nexport {pad2d} from './pad2d';\nexport {pad3d} from './pad3d';\nexport {pad4d} from './pad4d';\nexport {pool} from './pool';\nexport {pow} from './pow';\nexport {prelu} from './prelu';\nexport {print} from './print';\nexport {prod} from './prod';\nexport {raggedGather} from './ragged_gather';\nexport {raggedTensorToTensor} from './ragged_tensor_to_tensor';\nexport {rand} from './rand';\nexport {randomGamma} from './random_gamma';\nexport {randomNormal} from './random_normal';\nexport {randomStandardNormal} from './random_standard_normal';\nexport {randomUniform} from './random_uniform';\nexport {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 {upperBound} from './upper_bound';\nexport {variable} from './variable';\nexport {where} from './where';\nexport {whereAsync} from './where_async';\nexport {zeros} from './zeros';\nexport {zerosLike} from './zeros_like';\n\nexport * from './boolean_mask';\nexport * from './transpose';\nexport * from './norm';\nexport * from './moving_average';\nexport * from './scatter_nd';\nexport * from './search_sorted';\nexport * from './sparse_to_dense';\nexport * from './gather_nd';\nexport * from './dropout';\nexport * from './signal_ops_util';\nexport * from './in_top_k';\n\nexport {op, OP_SCOPE_SUFFIX} from './operation';\n\nimport {rfft} from './spectral/rfft';\nimport {fft} from './spectral/fft';\nimport {ifft} from './spectral/ifft';\nimport {irfft} from './spectral/irfft';\nconst spectral = {\n fft,\n ifft,\n rfft,\n irfft\n};\n\nimport * as fused from './fused_ops';\n\nimport {hammingWindow} from './signal/hamming_window';\nimport {hannWindow} from './signal/hann_window';\nimport {frame} from './signal/frame';\nimport {stft} from './signal/stft';\nconst signal = {\n hammingWindow,\n hannWindow,\n frame,\n stft,\n};\n\n// Image Ops namespace\nimport {cropAndResize} from './image/crop_and_resize';\nimport {flipLeftRight} from './image/flip_left_right';\nimport {grayscaleToRGB} from './image/grayscale_to_rgb';\nimport {rotateWithOffset} from './image/rotate_with_offset';\nimport {nonMaxSuppression} from './image/non_max_suppression';\nimport {nonMaxSuppressionAsync} from './image/non_max_suppression_async';\nimport {nonMaxSuppressionWithScore} from './image/non_max_suppression_with_score';\nimport {nonMaxSuppressionWithScoreAsync} from './image/non_max_suppression_with_score_async';\nimport {nonMaxSuppressionPadded} from './image/non_max_suppression_padded';\nimport {nonMaxSuppressionPaddedAsync} from './image/non_max_suppression_padded_async';\nimport {resizeBilinear} from './image/resize_bilinear';\nimport {resizeNearestNeighbor} from './image/resize_nearest_neighbor';\nimport {threshold} from './image/threshold';\nimport {transform} from './image/transform';\nconst image = {\n flipLeftRight,\n grayscaleToRGB,\n resizeNearestNeighbor,\n resizeBilinear,\n 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 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 // Not a legal value for DataType. Used to indicate a DataType field\n // has not been set.\n DT_INVALID = 0,\n\n // Data types that all computation devices are expected to be\n // capable to support.\n DT_FLOAT = 1,\n DT_DOUBLE = 2,\n DT_INT32 = 3,\n DT_UINT8 = 4,\n DT_INT16 = 5,\n DT_INT8 = 6,\n DT_STRING = 7,\n DT_COMPLEX64 = 8, // Single-precision complex\n DT_INT64 = 9,\n DT_BOOL = 10,\n DT_QINT8 = 11, // Quantized int8\n DT_QUINT8 = 12, // Quantized uint8\n DT_QINT32 = 13, // Quantized int32\n DT_BFLOAT16 = 14, // Float32 truncated to 16 bits. Only for cast ops.\n DT_QINT16 = 15, // Quantized int16\n DT_QUINT16 = 16, // Quantized uint16\n DT_UINT16 = 17,\n DT_COMPLEX128 = 18, // Double-precision complex\n DT_HALF = 19,\n DT_RESOURCE = 20,\n DT_VARIANT = 21, // Arbitrary C++ data types\n DT_UINT32 = 22,\n DT_UINT64 = 23,\n\n // Do not use! These are only for parameters. Every enum above\n // should have a corresponding value below (verified by types_test).\n DT_FLOAT_REF = 101,\n DT_DOUBLE_REF = 102,\n DT_INT32_REF = 103,\n DT_UINT8_REF = 104,\n DT_INT16_REF = 105,\n DT_INT8_REF = 106,\n DT_STRING_REF = 107,\n DT_COMPLEX64_REF = 108,\n DT_INT64_REF = 109,\n DT_BOOL_REF = 110,\n DT_QINT8_REF = 111,\n DT_QUINT8_REF = 112,\n DT_QINT32_REF = 113,\n DT_BFLOAT16_REF = 114,\n DT_QINT16_REF = 115,\n DT_QUINT16_REF = 116,\n DT_UINT16_REF = 117,\n DT_COMPLEX128_REF = 118,\n DT_HALF_REF = 119,\n DT_RESOURCE_REF = 120,\n DT_VARIANT_REF = 121,\n DT_UINT32_REF = 122,\n DT_UINT64_REF = 123,\n}\n\n/** Properties of a TensorShape. */\nexport declare interface ITensorShape {\n /** TensorShape dim */\n dim?: (TensorShape.IDim[]|null);\n\n /** TensorShape unknownRank */\n unknownRank?: (boolean|null);\n}\n\nexport namespace TensorShape {\n /** Properties of a Dim. */\n export declare interface IDim {\n /** Dim size */\n size?: (number|string|null);\n\n /** Dim name */\n name?: (string|null);\n }\n}\n\n/** Properties of a Tensor. */\nexport declare interface ITensor {\n /** Tensor dtype */\n dtype?: (DataType|null);\n\n /** Tensor tensorShape */\n tensorShape?: (ITensorShape|null);\n\n /** Tensor versionNumber */\n versionNumber?: (number|null);\n\n /** Tensor tensorContent */\n tensorContent?: (Uint8Array|null);\n\n /** Tensor floatVal */\n floatVal?: (number[]|null);\n\n /** Tensor doubleVal */\n doubleVal?: (number[]|null);\n\n /** Tensor intVal */\n intVal?: (number[]|null);\n\n /** Tensor stringVal */\n stringVal?: (Uint8Array[]|null);\n\n /** Tensor scomplexVal */\n scomplexVal?: (number[]|null);\n\n /** Tensor int64Val */\n int64Val?: ((number | string)[]|null);\n\n /** Tensor boolVal */\n boolVal?: (boolean[]|null);\n\n /** Tensor uint32Val */\n uint32Val?: (number[]|null);\n\n /** Tensor uint64Val */\n uint64Val?: ((number | string)[]|null);\n}\n\n/** Properties of an AttrValue. */\nexport declare interface IAttrValue {\n /** AttrValue list */\n list?: (AttrValue.IListValue|null);\n\n /** AttrValue s */\n s?: (string|null);\n\n /** AttrValue i */\n i?: (number|string|null);\n\n /** AttrValue f */\n f?: (number|null);\n\n /** AttrValue b */\n b?: (boolean|null);\n\n /** AttrValue type */\n type?: (DataType|null);\n\n /** AttrValue shape */\n shape?: (ITensorShape|null);\n\n /** AttrValue tensor */\n tensor?: (ITensor|null);\n\n /** AttrValue placeholder */\n placeholder?: (string|null);\n\n /** AttrValue func */\n func?: (INameAttrList|null);\n}\n\nexport namespace AttrValue {\n /** Properties of a ListValue. */\n export declare interface IListValue {\n /** ListValue s */\n s?: (string[]|null);\n\n /** ListValue i */\n i?: ((number | string)[]|null);\n\n /** ListValue f */\n f?: (number[]|null);\n\n /** ListValue b */\n b?: (boolean[]|null);\n\n /** ListValue type */\n type?: (DataType[]|null);\n\n /** ListValue shape */\n shape?: (ITensorShape[]|null);\n\n /** ListValue tensor */\n tensor?: (ITensor[]|null);\n\n /** ListValue func */\n func?: (INameAttrList[]|null);\n }\n}\n\n/** Properties of a NameAttrList. */\nexport declare interface INameAttrList {\n /** NameAttrList name */\n name?: (string|null);\n\n /** NameAttrList attr */\n attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a NodeDef. */\nexport declare interface INodeDef {\n /** NodeDef name */\n name?: (string|null);\n\n /** NodeDef op */\n op?: (string|null);\n\n /** NodeDef input */\n input?: (string[]|null);\n\n /** NodeDef device */\n device?: (string|null);\n\n /** NodeDef attr */\n attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a VersionDef. */\nexport declare interface IVersionDef {\n /** VersionDef producer */\n producer?: (number|null);\n\n /** VersionDef minConsumer */\n minConsumer?: (number|null);\n\n /** VersionDef badConsumers */\n badConsumers?: (number[]|null);\n}\n\n/** Properties of a GraphDef. */\nexport declare interface IGraphDef {\n /** GraphDef node */\n node?: (INodeDef[]|null);\n\n /** GraphDef versions */\n versions?: (IVersionDef|null);\n\n /** GraphDef library */\n library?: (IFunctionDefLibrary|null);\n}\n\n/** Properties of a CollectionDef. */\nexport declare interface ICollectionDef {\n /** CollectionDef nodeList */\n nodeList?: (CollectionDef.INodeList|null);\n\n /** CollectionDef bytesList */\n bytesList?: (CollectionDef.IBytesList|null);\n\n /** CollectionDef int64List */\n int64List?: (CollectionDef.IInt64List|null);\n\n /** CollectionDef floatList */\n floatList?: (CollectionDef.IFloatList|null);\n\n /** CollectionDef anyList */\n anyList?: (CollectionDef.IAnyList|null);\n}\n\nexport namespace CollectionDef {\n /** Properties of a NodeList. */\n export declare interface INodeList {\n /** NodeList value */\n value?: (string[]|null);\n }\n\n /** Properties of a BytesList. */\n export declare interface IBytesList {\n /** BytesList value */\n value?: (Uint8Array[]|null);\n }\n\n /** Properties of an Int64List. */\n export declare interface IInt64List {\n /** Int64List value */\n value?: ((number | string)[]|null);\n }\n\n /** Properties of a FloatList. */\n export declare interface IFloatList {\n /** FloatList value */\n value?: (number[]|null);\n }\n\n /** Properties of an AnyList. */\n export declare interface IAnyList {\n /** AnyList value */\n value?: (IAny[]|null);\n }\n}\n\n/** Properties of a SaverDef. */\nexport declare interface ISaverDef {\n /** SaverDef filenameTensorName */\n filenameTensorName?: (string|null);\n\n /** SaverDef saveTensorName */\n saveTensorName?: (string|null);\n\n /** SaverDef restoreOpName */\n restoreOpName?: (string|null);\n\n /** SaverDef maxToKeep */\n maxToKeep?: (number|null);\n\n /** SaverDef sharded */\n sharded?: (boolean|null);\n\n /** SaverDef keepCheckpointEveryNHours */\n keepCheckpointEveryNHours?: (number|null);\n\n /** SaverDef version */\n version?: (SaverDef.CheckpointFormatVersion|null);\n}\n\nexport namespace SaverDef {\n /** CheckpointFormatVersion enum. */\n export enum CheckpointFormatVersion {'LEGACY' = 0, 'V1' = 1, 'V2' = 2}\n}\n\n/** Properties of a TensorInfo. */\nexport declare interface ITensorInfo {\n /** TensorInfo name */\n name?: (string|null);\n\n /** TensorInfo cooSparse */\n cooSparse?: (TensorInfo.ICooSparse|null);\n\n /** TensorInfo dtype */\n dtype?: (DataType|null);\n\n /** TensorInfo tensorShape */\n tensorShape?: (ITensorShape|null);\n}\n\nexport namespace TensorInfo {\n /** Properties of a CooSparse. */\n export declare interface ICooSparse {\n /** CooSparse valuesTensorName */\n valuesTensorName?: (string|null);\n\n /** CooSparse indicesTensorName */\n indicesTensorName?: (string|null);\n\n /** CooSparse denseShapeTensorName */\n denseShapeTensorName?: (string|null);\n }\n}\n\n/** Properties of a SignatureDef. */\nexport declare interface ISignatureDef {\n /** SignatureDef inputs */\n inputs?: ({[k: string]: ITensorInfo}|null);\n\n /** SignatureDef outputs */\n outputs?: ({[k: string]: ITensorInfo}|null);\n\n /** SignatureDef methodName */\n methodName?: (string|null);\n}\n\n/** Properties of an AssetFileDef. */\nexport declare interface IAssetFileDef {\n /** AssetFileDef tensorInfo */\n tensorInfo?: (ITensorInfo|null);\n\n /** AssetFileDef filename */\n filename?: (string|null);\n}\n\n/** Properties of an OpDef. */\nexport declare interface IOpDef {\n /** OpDef name */\n name?: (string|null);\n\n /** OpDef inputArg */\n inputArg?: (OpDef.IArgDef[]|null);\n\n /** OpDef outputArg */\n outputArg?: (OpDef.IArgDef[]|null);\n\n /** OpDef attr */\n attr?: (OpDef.IAttrDef[]|null);\n\n /** OpDef deprecation */\n deprecation?: (OpDef.IOpDeprecation|null);\n\n /** OpDef summary */\n summary?: (string|null);\n\n /** OpDef description */\n description?: (string|null);\n\n /** OpDef isCommutative */\n isCommutative?: (boolean|null);\n\n /** OpDef isAggregate */\n isAggregate?: (boolean|null);\n\n /** OpDef isStateful */\n isStateful?: (boolean|null);\n\n /** OpDef allowsUninitializedInput */\n allowsUninitializedInput?: (boolean|null);\n}\n\nexport namespace OpDef {\n /** Properties of an ArgDef. */\n export declare interface IArgDef {\n /** ArgDef name */\n name?: (string|null);\n\n /** ArgDef description */\n description?: (string|null);\n\n /** ArgDef type */\n type?: (DataType|null);\n\n /** ArgDef typeAttr */\n typeAttr?: (string|null);\n\n /** ArgDef numberAttr */\n numberAttr?: (string|null);\n\n /** ArgDef typeListAttr */\n typeListAttr?: (string|null);\n\n /** ArgDef isRef */\n isRef?: (boolean|null);\n }\n\n /** Properties of an AttrDef. */\n export declare interface IAttrDef {\n /** AttrDef name */\n name?: (string|null);\n\n /** AttrDef type */\n type?: (string|null);\n\n /** AttrDef defaultValue */\n defaultValue?: (IAttrValue|null);\n\n /** AttrDef description */\n description?: (string|null);\n\n /** AttrDef hasMinimum */\n hasMinimum?: (boolean|null);\n\n /** AttrDef minimum */\n minimum?: (number|string|null);\n\n /** AttrDef allowedValues */\n allowedValues?: (IAttrValue|null);\n }\n\n /** Properties of an OpDeprecation. */\n export declare interface IOpDeprecation {\n /** OpDeprecation version */\n version?: (number|null);\n\n /** OpDeprecation explanation */\n explanation?: (string|null);\n }\n}\n\n/** Properties of an OpList. */\nexport declare interface IOpList {\n /** OpList op */\n op?: (IOpDef[]|null);\n}\n\n/** Properties of a MetaGraphDef. */\nexport declare interface IMetaGraphDef {\n /** MetaGraphDef metaInfoDef */\n metaInfoDef?: (MetaGraphDef.IMetaInfoDef|null);\n\n /** MetaGraphDef graphDef */\n graphDef?: (IGraphDef|null);\n\n /** MetaGraphDef saverDef */\n saverDef?: (ISaverDef|null);\n\n /** MetaGraphDef collectionDef */\n collectionDef?: ({[k: string]: ICollectionDef}|null);\n\n /** MetaGraphDef signatureDef */\n signatureDef?: ({[k: string]: ISignatureDef}|null);\n\n /** MetaGraphDef assetFileDef */\n assetFileDef?: (IAssetFileDef[]|null);\n}\n\nexport namespace MetaGraphDef {\n /** Properties of a MetaInfoDef. */\n export declare interface IMetaInfoDef {\n /** MetaInfoDef metaGraphVersion */\n metaGraphVersion?: (string|null);\n\n /** MetaInfoDef strippedOpList */\n strippedOpList?: (IOpList|null);\n\n /** MetaInfoDef anyInfo */\n anyInfo?: (IAny|null);\n\n /** MetaInfoDef tags */\n tags?: (string[]|null);\n\n /** MetaInfoDef tensorflowVersion */\n tensorflowVersion?: (string|null);\n\n /** MetaInfoDef tensorflowGitVersion */\n tensorflowGitVersion?: (string|null);\n }\n}\n\n/** Properties of a SavedModel. */\nexport declare interface ISavedModel {\n /** SavedModel savedModelSchemaVersion */\n savedModelSchemaVersion?: (number|string|null);\n\n /** SavedModel metaGraphs */\n metaGraphs?: (IMetaGraphDef[]|null);\n}\n\n/** Properties of a FunctionDefLibrary. */\nexport declare interface IFunctionDefLibrary {\n /** FunctionDefLibrary function */\n 'function'?: (IFunctionDef[]|null);\n\n /** FunctionDefLibrary gradient */\n gradient?: (IGradientDef[]|null);\n}\n\n/** Properties of a FunctionDef. */\nexport declare interface IFunctionDef {\n /** FunctionDef signature */\n signature?: (IOpDef|null);\n\n /** FunctionDef attr */\n attr?: ({[k: string]: IAttrValue}|null);\n\n /** FunctionDef nodeDef */\n nodeDef?: (INodeDef[]|null);\n\n /** FunctionDef ret */\n ret?: ({[k: string]: string}|null);\n}\n\n/** Properties of a GradientDef. */\nexport declare interface IGradientDef {\n /** GradientDef functionName */\n functionName?: (string|null);\n\n /** GradientDef gradientFunc */\n gradientFunc?: (string|null);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nconst ENV = env();\n\n/** Whether to keep intermediate tensors. */\nENV.registerFlag('KEEP_INTERMEDIATE_TENSORS', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Keep intermediate tensors is ON. This will print the values of all ' +\n 'intermediate tensors during model inference. Not all models ' +\n 'support this mode. For details, check e2e/benchmarks/ ' +\n 'model_config.js. This significantly impacts performance.');\n }\n});\n","\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpExecutor, OpMapper} from '../types';\n\nconst CUSTOM_OPS: {[key: string]: OpMapper} = {};\n\n/**\n * Register an Op for graph model executor. This allows you to register\n * TensorFlow custom op or override existing op.\n *\n * Here is an example of registering a new MatMul Op.\n * ```js\n * const customMatmul = (node) =>\n * tf.matMul(\n * node.inputs[0], node.inputs[1],\n * node.attrs['transpose_a'], node.attrs['transpose_b']);\n *\n * tf.registerOp('MatMul', customMatmul);\n * ```\n * The inputs and attrs of the node object are based on the TensorFlow op\n * registry.\n *\n * @param name The Tensorflow Op name.\n * @param opFunc An op function which is called with the current graph node\n * during execution and needs to return a tensor or a list of tensors. The node\n * has the following attributes:\n * - attr: A map from attribute name to its value\n * - inputs: A list of input tensors\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function registerOp(name: string, opFunc: OpExecutor) {\n const opMapper: OpMapper = {\n tfOpName: name,\n category: 'custom',\n inputs: [],\n attrs: [],\n customExecutor: opFunc\n };\n\n CUSTOM_OPS[name] = opMapper;\n}\n\n/**\n * Retrieve the OpMapper object for the registered op.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function getRegisteredOp(name: string): OpMapper {\n return CUSTOM_OPS[name];\n}\n\n/**\n * Deregister the Op for graph model executor.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function deregisterOp(name: string) {\n delete CUSTOM_OPS[name];\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {clone, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {ResourceManager} from '../../executor/resource_manager';\nimport {Node, ValueType} from '../types';\n\nexport function getParamValue(\n paramName: string, node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, resourceManager?: ResourceManager): ValueType {\n const inputParam = node.inputParams[paramName];\n if (inputParam && inputParam.inputIndexStart !== undefined) {\n const start = inputParam.inputIndexStart;\n const end = inputParam.inputIndexEnd === 0 ?\n undefined :\n (inputParam.inputIndexEnd === undefined ? start + 1 :\n inputParam.inputIndexEnd);\n 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/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Add',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'AddV2',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'AddN',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'BiasAdd',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sub',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'RealDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Div',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'DivNoNan',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FloorDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Mul',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Maximum',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Minimum',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Pow',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'SquaredDifference',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Mod',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FloorMod',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Abs',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Acos',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Asin',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Atan',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Atan2',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'y',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Ceil',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ClipByValue',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'clipValueMin',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'clipValueMax',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Complex',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'real',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'imag',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ComplexAbs',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Cos',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Cosh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Elu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Exp',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Floor',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Log',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Imag',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'outputType',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Neg',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Real',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'outputType',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Prelu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'alpha',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Relu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Relu6',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Selu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sigmoid',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sin',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sinh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sqrt',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Rsqrt',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Square',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tan',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tanh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sign',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Round',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Expm1',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Log1p',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Reciprocal',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Softplus',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Asinh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Acosh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Atanh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Erf',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axes',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool',\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LeakyRelu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 0.2\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IsNan',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'EmptyTensorList',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 1,\n 'name': 'maxNumElements',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'LoopCond',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'pred',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Switch',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'pred',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Merge',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'Enter',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'frame_name',\n 'name': 'frameName',\n 'type': 'string'\n },\n {\n 'tfName': 'is_constant',\n 'name': 'isConstant',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Exit',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'NextIteration',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'size',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'tfName': 'dynamic_size',\n 'name': 'dynamicSize',\n 'type': 'bool'\n },\n {\n 'tfName': 'clear_after_read',\n 'name': 'clearAfterRead',\n 'type': 'bool'\n },\n {\n 'tfName': 'identical_element_shapes',\n 'name': 'identicalElementShapes',\n 'type': 'bool'\n },\n {\n 'tfName': 'tensor_array_name',\n 'name': 'name',\n 'type': 'string'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayWriteV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayReadV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayGatherV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayScatterV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayConcatV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'element_shape_except0',\n 'name': 'elementShapeExcept0',\n 'type': 'shape',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArraySplitV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'lengths',\n 'type': 'number[]'\n },\n {\n 'start': 3,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArraySizeV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayCloseV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'StatelessIf',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'cond',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'then_branch',\n 'name': 'thenBranch',\n 'type': 'func'\n },\n {\n 'tfName': 'else_branch',\n 'name': 'elseBranch',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'If',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'cond',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'then_branch',\n 'name': 'thenBranch',\n 'type': 'func'\n },\n {\n 'tfName': 'else_branch',\n 'name': 'elseBranch',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'StatelessWhile',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'cond',\n 'name': 'cond',\n 'type': 'func'\n },\n {\n 'tfName': 'body',\n 'name': 'body',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'While',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'cond',\n 'name': 'cond',\n 'type': 'func'\n },\n {\n 'tfName': 'body',\n 'name': 'body',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListScatter',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListScatterV2',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 3,\n 'name': 'numElements',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListGather',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListGetItem',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListSetItem',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListReserve',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 1,\n 'name': 'numElements',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListFromTensor',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListStack',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n },\n {\n 'tfName': 'num_elements',\n 'name': 'numElements',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListSplit',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 2,\n 'name': 'lengths',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListConcat',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListConcatV2',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListPopBack',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListPushBack',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListLength',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListResize',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'AvgPool',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MaxPool',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': [],\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MaxPoolWithArgmax',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'include_batch_in_index',\n 'name': 'includeBatchInIndex',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'AvgPool3D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MaxPool3D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Conv1D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'stride',\n 'name': 'stride',\n 'type': 'number'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NWC'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'dilation',\n 'name': 'dilation',\n 'type': 'number',\n 'defaultValue': 1\n }\n ]\n },\n {\n 'tfOpName': 'Conv2D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'useCudnnOnGpu',\n 'name': 'useCudnnOnGpu',\n 'type': 'bool'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': '_FusedConv2D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_args',\n 'name': 'numArgs',\n 'type': 'number'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'use_cudnn_on_gpu',\n 'name': 'useCudnnOnGpu',\n 'type': 'bool',\n 'defaultValue': true\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'defaultValue': [\n 1,\n 1,\n 1,\n 1\n ]\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.0001\n },\n {\n 'tfName': 'leakyrelu_alpha',\n 'name': 'leakyreluAlpha',\n 'type': 'number',\n 'defaultValue': 0.2\n }\n ]\n },\n {\n 'tfOpName': 'Conv2DBackpropInput',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 2,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n },\n {\n 'start': 0,\n 'name': 'outputShape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2d',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'FusedDepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_args',\n 'name': 'numArgs',\n 'type': 'number'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'defaultValue': [\n 1,\n 1,\n 1,\n 1\n ]\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n }\n ]\n },\n {\n 'tfOpName': 'Conv3D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Dilation2D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'rates',\n 'name': 'dilations',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Fill',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n },\n {\n 'start': 1,\n 'name': 'value',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'LinSpace',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'start',\n 'type': 'number'\n },\n {\n 'start': 1,\n 'name': 'stop',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'num',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'OneHot',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'depth',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'onValue',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'start': 3,\n 'name': 'offValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Ones',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'OnesLike',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'RandomStandardNormal',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'T',\n 'name': 'T',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'RandomUniform',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'minval',\n 'name': 'minval',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'maxval',\n 'name': 'maxval',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'T',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Range',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'start',\n 'type': 'number'\n },\n {\n 'start': 1,\n 'name': 'stop',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'step',\n 'type': 'number',\n 'defaultValue': 0\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tidx',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TruncatedNormal',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'means',\n 'name': 'mean',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'stddev',\n 'name': 'stdDev',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number'\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'T',\n 'name': 'T',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Zeros',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'ZerosLike',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Multinomial',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'logits',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'numSamples',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number'\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'output_dtype',\n 'name': 'output_dtype',\n 'type': 'dtype'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'NonMaxSuppressionV2',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV3',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n },\n {\n 'start': 4,\n 'name': 'scoreThreshold',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV4',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n },\n {\n 'start': 4,\n 'name': 'scoreThreshold',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'T_threshold',\n 'name': 'threshold',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'pad_to_max_output_size',\n 'name': 'padToMaxOutputSize',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV5',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n },\n {\n 'start': 4,\n 'name': 'scoreThreshold',\n 'type': 'number'\n },\n {\n 'start': 5,\n 'name': 'softNmsSigma',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'Where',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'condition',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ListDiff',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'y',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'LowerBound',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sortedSequence',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'TopKV2',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'k',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'sorted',\n 'name': 'sorted',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'UpperBound',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sortedSequence',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Unique',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'UniqueV2',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'PlaceholderWithDefault',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'default',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'shape',\n 'name': 'shape',\n 'type': 'shape'\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Placeholder',\n 'category': 'graph',\n 'attrs': [\n {\n 'tfName': 'shape',\n 'name': 'shape',\n 'type': 'shape'\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Const',\n 'category': 'graph'\n },\n {\n 'tfOpName': 'Identity',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'IdentityN',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'x',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'Snapshot',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Rank',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Size',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Shape',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'ShapeN',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'x',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'Print',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'data',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'message',\n 'name': 'message',\n 'type': 'string'\n },\n {\n 'tfName': 'first_n',\n 'name': 'firstN',\n 'type': 'number',\n 'notSupported': true\n },\n {\n 'tfName': 'summarize',\n 'name': 'summarize',\n 'type': 'number',\n 'defaultValue': 3\n }\n ]\n },\n {\n 'tfOpName': 'NoOp',\n 'category': 'graph',\n 'inputs': []\n },\n {\n 'tfOpName': 'StopGradient',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'FakeQuantWithMinMaxVars',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'min',\n 'name': 'min',\n 'type': 'number'\n },\n {\n 'tfName': 'max',\n 'name': 'max',\n 'type': 'number'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'HashTable',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {\n 'tfName': 'shared_name',\n 'name': 'sharedName',\n 'type': 'string'\n },\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {\n 'tfName': 'key_dtype',\n 'name': 'keyDType',\n 'type': 'dtype'\n },\n {\n 'tfName': 'value_dtype',\n 'name': 'valueDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'HashTableV2',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {\n 'tfName': 'shared_name',\n 'name': 'sharedName',\n 'type': 'string'\n },\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {\n 'tfName': 'key_dtype',\n 'name': 'keyDType',\n 'type': 'dtype'\n },\n {\n 'tfName': 'value_dtype',\n 'name': 'valueDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableImport',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableImportV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableFind',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableFindV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableSize',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableSizeV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'ResizeBilinear',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'images',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'align_corners',\n 'name': 'alignCorners',\n 'type': 'bool'\n },\n {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ResizeNearestNeighbor',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'images',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'align_corners',\n 'name': 'alignCorners',\n 'type': 'bool'\n },\n {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'CropAndResize',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'image',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'boxInd',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'cropSize',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'method',\n 'name': 'method',\n 'type': 'string'\n },\n {\n 'tfName': 'extrapolation_value',\n 'name': 'extrapolationValue',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'ImageProjectiveTransformV3',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'images',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'transforms',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'outputShape',\n 'type': 'number[]'\n },\n {\n 'start': 3,\n 'name': 'fillValue',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'interpolation',\n 'name': 'interpolation',\n 'type': 'string'\n },\n {\n 'tfName': 'fill_mode',\n 'name': 'fillMode',\n 'type': 'string'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Equal',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'NotEqual',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Greater',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'GreaterEqual',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Less',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LessEqual',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LogicalAnd',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LogicalNot',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LogicalOr',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Select',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'condition',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'SelectV2',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'condition',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': '_FusedMatMul',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_args',\n 'name': 'numArgs',\n 'type': 'number'\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.0001\n },\n {\n 'tfName': 'transpose_a',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'transpose_b',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'leakyrelu_alpha',\n 'name': 'leakyreluAlpha',\n 'type': 'number',\n 'defaultValue': 0.2\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MatMul',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'transpose_a',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'transpose_b',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'BatchMatMul',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'adj_x',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'adj_y',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'BatchMatMulV2',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'adj_x',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'adj_y',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Transpose',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'perm',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Einsum',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'equation',\n 'name': 'equation',\n 'type': 'string'\n },\n {\n 'tfName': 'N',\n 'name': 'n',\n 'type': 'number',\n 'defaultValue': 2\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'EuclideanNorm',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool',\n 'defaultValue': false\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNorm',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scale',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'offset',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'mean',\n 'type': 'tensor'\n },\n {\n 'start': 4,\n 'name': 'variance',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNormV2',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scale',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'offset',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'mean',\n 'type': 'tensor'\n },\n {\n 'start': 4,\n 'name': 'variance',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNormV3',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scale',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'offset',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'mean',\n 'type': 'tensor'\n },\n {\n 'start': 4,\n 'name': 'variance',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LRN',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'depth_radius',\n 'name': 'radius',\n 'type': 'number',\n 'defaultValue': 5\n },\n {\n 'tfName': 'bias',\n 'name': 'bias',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'beta',\n 'name': 'beta',\n 'type': 'number',\n 'defaultValue': 0.5\n }\n ]\n },\n {\n 'tfOpName': 'Softmax',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'LogSoftmax',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sparseIndices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'outputShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'sparseValues',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': true,\n 'notSupported': true\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Bincount',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'weights',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'DenseBincount',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'weights',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'binary_output',\n 'name': 'binaryOutput',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Max',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Mean',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Min',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Sum',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'All',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Any',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'ArgMax',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'ArgMin',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Cumprod',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'exclusive',\n 'name': 'exclusive',\n 'type': 'bool'\n },\n {\n 'tfName': 'reverse',\n 'name': 'reverse',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Cumsum',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'exclusive',\n 'name': 'exclusive',\n 'type': 'bool'\n },\n {\n 'tfName': 'reverse',\n 'name': 'reverse',\n 'type': 'bool'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'ConcatV2',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'end': -1,\n 'name': 'tensors',\n 'type': 'tensors'\n },\n {\n 'start': -1,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'N',\n 'name': 'n',\n 'type': 'number',\n 'defaultValue': 2\n }\n ]\n },\n {\n 'tfOpName': 'Concat',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 1,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n },\n {\n 'start': 0,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'N',\n 'name': 'n',\n 'type': 'number',\n 'defaultValue': 2\n }\n ]\n },\n {\n 'tfOpName': 'GatherV2',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n }\n ],\n 'attrs': [\n {\n 'tfName': 'batch_dims',\n 'name': 'batchDims',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Gather',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Reverse',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'dims',\n 'type': 'bool[]'\n }\n ]\n },\n {\n 'tfOpName': 'ReverseV2',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Slice',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'begin',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'size',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'StridedSlice',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'begin',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'end',\n 'type': 'number[]'\n },\n {\n 'start': 3,\n 'name': 'strides',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'begin_mask',\n 'name': 'beginMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'end_mask',\n 'name': 'endMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'new_axis_mask',\n 'name': 'newAxisMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'ellipsis_mask',\n 'name': 'ellipsisMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'shrink_axis_mask',\n 'name': 'shrinkAxisMask',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Pack',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Unpack',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'num',\n 'name': 'num',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tile',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'reps',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Split',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'start': 1,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_split',\n 'name': 'numOrSizeSplits',\n 'type': 'number',\n 'defaultValue': 1\n }\n ]\n },\n {\n 'tfOpName': 'SplitV',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'numOrSizeSplits',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'ScatterNd',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'GatherNd',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sparseIndices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'outputShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'sparseValues',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': false,\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'SparseFillEmptyRows',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'denseShape',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseReshape',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'inputIndices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'inputShape',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'newShape',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'SparseSegmentMean',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'segmentIds',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseSegmentSum',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'segmentIds',\n 'type': 'tensor'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'FFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'IFFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'RFFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IRFFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'StringNGrams',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'dataSplits',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'separator',\n 'name': 'separator',\n 'type': 'string'\n },\n {\n 'tfName': 'ngram_widths',\n 'name': 'nGramWidths',\n 'type': 'number[]'\n },\n {\n 'tfName': 'left_pad',\n 'name': 'leftPad',\n 'type': 'string'\n },\n {\n 'tfName': 'right_pad',\n 'name': 'rightPad',\n 'type': 'string'\n },\n {\n 'tfName': 'pad_width',\n 'name': 'padWidth',\n 'type': 'number'\n },\n {\n 'tfName': 'preserve_short_sequences',\n 'name': 'preserveShortSequences',\n 'type': 'bool'\n }\n ],\n 'outputs': [\n 'ngrams',\n 'ngrams_splits'\n ]\n },\n {\n 'tfOpName': 'StringSplit',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'delimiter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'skip_empty',\n 'name': 'skipEmpty',\n 'type': 'bool'\n }\n ],\n 'outputs': [\n 'indices',\n 'values',\n 'shape'\n ]\n },\n {\n 'tfOpName': 'StringToHashBucketFast',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_buckets',\n 'name': 'numBuckets',\n 'type': 'number'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Cast',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'SrcT',\n 'name': 'sdtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'DstT',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'ExpandDims',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'MirrorPad',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'padding',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'mode',\n 'name': 'mode',\n 'type': 'string'\n }\n ]\n },\n {\n 'tfOpName': 'Pad',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'padding',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'constant_value',\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'PadV2',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'padding',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Reshape',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Squeeze',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'tfDeprecatedName': 'squeeze_dims',\n 'name': 'axis',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'SpaceToBatchND',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'blockShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'paddings',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'BatchToSpaceND',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'blockShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'crops',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'DepthToSpace',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'block_size',\n 'name': 'blockSize',\n 'type': 'number'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string'\n }\n ]\n },\n {\n 'tfOpName': 'BroadcastTo',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': []\n },\n {\n 'tfOpName': 'BroadcastArgs',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 's0',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 's1',\n 'type': 'tensor'\n }\n ],\n 'attrs': []\n }\n];\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, env} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\n\nimport {getRegisteredOp} from './custom_op/register';\nimport {getNodeNameAndIndex} from './executors/utils';\nimport * as arithmetic from './op_list/arithmetic';\nimport * as basicMath from './op_list/basic_math';\nimport * as control from './op_list/control';\nimport * as convolution from './op_list/convolution';\nimport * as creation from './op_list/creation';\nimport * as dynamic from './op_list/dynamic';\nimport * as evaluation from './op_list/evaluation';\nimport * as graph from './op_list/graph';\nimport * as hashTable from './op_list/hash_table';\nimport * as image from './op_list/image';\nimport * as logical from './op_list/logical';\nimport * as matrices from './op_list/matrices';\nimport * as normalization from './op_list/normalization';\nimport * as reduction from './op_list/reduction';\nimport * as sliceJoin from './op_list/slice_join';\nimport * as sparse from './op_list/sparse';\nimport * as spectral from './op_list/spectral';\nimport * as string from './op_list/string';\nimport * as transformation from './op_list/transformation';\nimport {Graph, InputParamValue, Node, OpMapper, ParamValue} from './types';\n\nexport class OperationMapper {\n private static _instance: OperationMapper;\n\n private opMappers: {[key: string]: OpMapper};\n\n // Singleton instance for the mapper\n public static get Instance() {\n return this._instance || (this._instance = new this());\n }\n\n // Loads the op mapping from the JSON file.\n private constructor() {\n const ops = [\n arithmetic, basicMath, control, convolution, creation, dynamic,\n evaluation, graph, hashTable, image, logical, matrices, normalization,\n reduction, sliceJoin, sparse, spectral, string, transformation\n ];\n const mappersJson: OpMapper[] = [].concat(...ops.map(op => op.json));\n\n this.opMappers = mappersJson.reduce<{[key: string]: OpMapper}>(\n (map, mapper: OpMapper) => {\n map[mapper.tfOpName] = mapper;\n return map;\n },\n {});\n }\n\n // Converts the model inference graph from Tensorflow GraphDef to local\n // representation for TensorFlow.js API\n transformGraph(\n graph: tensorflow.IGraphDef,\n signature: tensorflow.ISignatureDef = {}): Graph {\n const tfNodes = graph.node;\n const placeholders: Node[] = [];\n const weights: Node[] = [];\n const initNodes: Node[] = [];\n const nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n map[node.name] = this.mapNode(node);\n if (node.op.startsWith('Placeholder')) {\n placeholders.push(map[node.name]);\n } else if (node.op === 'Const') {\n weights.push(map[node.name]);\n } else if (node.input == null || node.input.length === 0) {\n initNodes.push(map[node.name]);\n }\n return map;\n }, {});\n\n let inputs: Node[] = [];\n const outputs: Node[] = [];\n let inputNodeNameToKey: {[key: string]: string} = {};\n let outputNodeNameToKey: {[key: string]: string} = {};\n if (signature != null) {\n inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);\n outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);\n }\n const allNodes = Object.keys(nodes);\n allNodes.forEach(key => {\n const node = nodes[key];\n node.inputNames.forEach((name, index) => {\n const [nodeName, , outputName] = getNodeNameAndIndex(name);\n const inputNode = nodes[nodeName];\n if (inputNode.outputs != null) {\n const outputIndex = inputNode.outputs.indexOf(outputName);\n if (outputIndex !== -1) {\n const inputName = `${nodeName}:${outputIndex}`;\n // update the input name to use the mapped output index directly.\n node.inputNames[index] = inputName;\n }\n }\n node.inputs.push(inputNode);\n inputNode.children.push(node);\n });\n });\n\n // if signature has not outputs set, add any node that does not have\n // outputs.\n if (Object.keys(outputNodeNameToKey).length === 0) {\n allNodes.forEach(key => {\n const node = nodes[key];\n if (node.children.length === 0) {\n outputs.push(node);\n }\n });\n } else {\n Object.keys(outputNodeNameToKey).forEach(name => {\n const [nodeName, ] = getNodeNameAndIndex(name);\n const node = nodes[nodeName];\n if (node != null) {\n node.signatureKey = outputNodeNameToKey[name];\n outputs.push(node);\n }\n });\n }\n\n if (Object.keys(inputNodeNameToKey).length > 0) {\n Object.keys(inputNodeNameToKey).forEach(name => {\n const [nodeName, ] = getNodeNameAndIndex(name);\n const node = nodes[nodeName];\n if (node) {\n node.signatureKey = inputNodeNameToKey[name];\n inputs.push(node);\n }\n });\n } else {\n inputs = placeholders;\n }\n\n let functions = {};\n if (graph.library != null && graph.library.function != null) {\n functions = graph.library.function.reduce((functions, func) => {\n functions[func.signature.name] = this.mapFunction(func);\n return functions;\n }, {} as {[key: string]: Graph});\n }\n\n const result: Graph =\n {nodes, inputs, outputs, weights, placeholders, signature, functions};\n\n if (initNodes.length > 0) {\n result.initNodes = initNodes;\n }\n\n return result;\n }\n\n private mapSignatureEntries(entries: {[k: string]: tensorflow.ITensorInfo}) {\n return Object.keys(entries || {})\n .reduce<{[key: string]: string}>((prev, curr) => {\n prev[entries[curr].name] = curr;\n return prev;\n }, {});\n }\n\n private mapNode(node: tensorflow.INodeDef): Node {\n // Unsupported ops will cause an error at run-time (not parse time), since\n // they may not be used by the actual execution subgraph.\n const mapper =\n getRegisteredOp(node.op) || this.opMappers[node.op] || {} as OpMapper;\n if (node.attr == null) {\n node.attr = {};\n }\n\n const newNode: Node = {\n name: node.name,\n op: node.op,\n category: mapper.category,\n inputNames:\n (node.input ||\n []).map(input => input.startsWith('^') ? input.slice(1) : input),\n inputs: [],\n children: [],\n inputParams: {},\n attrParams: {},\n rawAttrs: node.attr,\n outputs: mapper.outputs\n };\n\n if (mapper.inputs != null) {\n newNode.inputParams =\n mapper.inputs.reduce<{[key: string]: InputParamValue}>(\n (map, param) => {\n map[param.name] = {\n type: param.type,\n inputIndexStart: param.start,\n inputIndexEnd: param.end\n };\n return map;\n },\n {});\n }\n if (mapper.attrs != null) {\n newNode.attrParams =\n mapper.attrs.reduce<{[key: string]: ParamValue}>((map, param) => {\n const type = param.type;\n let value = undefined;\n switch (param.type) {\n case 'string':\n value = getStringParam(\n node.attr, param.tfName, param.defaultValue as string);\n\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getStringParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string);\n }\n break;\n case 'string[]':\n value = getStringArrayParam(\n node.attr, param.tfName, param.defaultValue as string[]);\n\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getStringArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string[]);\n }\n break;\n case 'number':\n value = getNumberParam(\n node.attr, param.tfName,\n (param.defaultValue || 0) as number);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getNumberParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number);\n }\n break;\n case 'number[]':\n value = getNumericArrayParam(\n node.attr, param.tfName, param.defaultValue as number[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getNumericArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[]);\n }\n break;\n case 'bool':\n value = getBoolParam(\n node.attr, param.tfName, param.defaultValue as boolean);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getBoolParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as boolean);\n }\n break;\n case 'bool[]':\n value = getBoolArrayParam(\n node.attr, param.tfName, param.defaultValue as boolean[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getBoolArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as boolean[]);\n }\n break;\n case 'shape':\n value = getTensorShapeParam(\n node.attr, param.tfName, param.defaultValue as number[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getTensorShapeParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[]);\n }\n break;\n case 'shape[]':\n value = getTensorShapeArrayParam(\n node.attr, param.tfName, param.defaultValue as number[][]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getTensorShapeArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[][]);\n }\n break;\n case 'dtype':\n value = getDtypeParam(\n node.attr, param.tfName, param.defaultValue as DataType);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getDtypeParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as DataType);\n }\n break;\n case 'dtype[]':\n value = getDtypeArrayParam(\n node.attr, param.tfName, param.defaultValue as DataType[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getDtypeArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as DataType[]);\n }\n break;\n case 'func':\n value = getFuncParam(\n node.attr, param.tfName, param.defaultValue as string);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getFuncParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string);\n }\n break;\n case 'tensor':\n case 'tensors':\n break;\n default:\n throw new Error(\n `Unsupported param type: ${param.type} for op: ${node.op}`);\n }\n map[param.name] = {value, type};\n return map;\n }, {});\n }\n return newNode;\n }\n\n // map the TFunctionDef to TFJS graph object\n private mapFunction(functionDef: tensorflow.IFunctionDef): Graph {\n const tfNodes = functionDef.nodeDef;\n const placeholders: Node[] = [];\n const weights: Node[] = [];\n let nodes: {[key: string]: Node} = {};\n if (tfNodes != null) {\n nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n map[node.name] = this.mapNode(node);\n if (node.op === 'Const') {\n weights.push(map[node.name]);\n }\n return map;\n }, {});\n }\n const inputs: Node[] = [];\n const outputs: Node[] = [];\n\n functionDef.signature.inputArg.forEach(arg => {\n const [nodeName, ] = getNodeNameAndIndex(arg.name);\n const node: Node = {\n name: nodeName,\n op: 'Placeholder',\n inputs: [],\n inputNames: [],\n category: 'graph',\n inputParams: {},\n attrParams: {dtype: {value: parseDtypeParam(arg.type), type: 'dtype'}},\n children: []\n };\n node.signatureKey = arg.name;\n inputs.push(node);\n nodes[nodeName] = node;\n });\n\n const allNodes = Object.keys(nodes);\n allNodes.forEach(key => {\n const node = nodes[key];\n node.inputNames.forEach((name, index) => {\n const [nodeName, , outputName] = getNodeNameAndIndex(name);\n const inputNode = nodes[nodeName];\n if (inputNode.outputs != null) {\n const outputIndex = inputNode.outputs.indexOf(outputName);\n if (outputIndex !== -1) {\n const inputName = `${nodeName}:${outputIndex}`;\n // update the input name to use the mapped output index directly.\n node.inputNames[index] = inputName;\n }\n }\n node.inputs.push(inputNode);\n inputNode.children.push(node);\n });\n });\n\n const returnNodeMap = functionDef.ret;\n\n functionDef.signature.outputArg.forEach(output => {\n const [nodeName, index] = getNodeNameAndIndex(returnNodeMap[output.name]);\n const node = nodes[nodeName];\n if (node != null) {\n node.defaultOutput = index;\n outputs.push(node);\n }\n });\n\n const signature = this.mapArgsToSignature(functionDef);\n return {nodes, inputs, outputs, weights, placeholders, signature};\n }\n\n private mapArgsToSignature(functionDef: tensorflow.IFunctionDef):\n tensorflow.ISignatureDef {\n return {\n methodName: functionDef.signature.name,\n inputs: functionDef.signature.inputArg.reduce(\n (map, arg) => {\n map[arg.name] = this.mapArgToTensorInfo(arg);\n return map;\n },\n {} as {[key: string]: tensorflow.ITensorInfo}),\n outputs: functionDef.signature.outputArg.reduce(\n (map, arg) => {\n map[arg.name] = this.mapArgToTensorInfo(arg, functionDef.ret);\n return map;\n },\n {} as {[key: string]: tensorflow.ITensorInfo}),\n };\n }\n\n private mapArgToTensorInfo(\n arg: tensorflow.OpDef.IArgDef,\n nameMap?: {[key: string]: string}): tensorflow.ITensorInfo {\n let name = arg.name;\n if (nameMap != null) {\n name = nameMap[name];\n }\n return {name, dtype: arg.type};\n }\n}\n\nexport function decodeBase64(text: string): string {\n const global = env().global;\n if (typeof global.atob !== 'undefined') {\n return global.atob(text);\n } else if (typeof Buffer !== 'undefined') {\n return new Buffer(text, 'base64').toString();\n } else {\n throw new Error(\n 'Unable to decode base64 in this environment. ' +\n 'Missing built-in atob() or Buffer()');\n }\n}\n\nexport function parseStringParam(s: []|string, keepCase: boolean): string {\n const value =\n Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);\n return keepCase ? value : value.toLowerCase();\n}\n\nexport function getStringParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string,\n keepCase = false): string {\n const param = attrs[name];\n if (param != null) {\n return parseStringParam(param.s, keepCase);\n }\n return def;\n}\n\nexport function getBoolParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: boolean): boolean {\n const param = attrs[name];\n return param ? param.b : def;\n}\n\nexport function getNumberParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number): number {\n const param = attrs[name] || {};\n const value =\n param['i'] != null ? param['i'] : (param['f'] != null ? param['f'] : def);\n return (typeof value === 'number') ? value : parseInt(value, 10);\n}\n\nexport function parseDtypeParam(value: string|tensorflow.DataType): DataType {\n if (typeof (value) === 'string') {\n // tslint:disable-next-line:no-any\n value = tensorflow.DataType[value as any];\n }\n switch (value) {\n case tensorflow.DataType.DT_FLOAT:\n case tensorflow.DataType.DT_HALF:\n return 'float32';\n case tensorflow.DataType.DT_INT32:\n case tensorflow.DataType.DT_INT64:\n case tensorflow.DataType.DT_INT8:\n case tensorflow.DataType.DT_UINT8:\n return 'int32';\n case tensorflow.DataType.DT_BOOL:\n return 'bool';\n case tensorflow.DataType.DT_DOUBLE:\n return 'float32';\n case tensorflow.DataType.DT_STRING:\n return 'string';\n default:\n // Unknown dtype error will happen at runtime (instead of parse time),\n // since these nodes might not be used by the actual subgraph execution.\n return null;\n }\n}\n\nexport function getFuncParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: string): string {\n const param = attrs[name];\n if (param && param.func) {\n return param.func.name;\n }\n return def;\n}\n\nexport function getDtypeParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: DataType): DataType {\n const param = attrs[name];\n if (param && param.type) {\n return parseDtypeParam(param.type);\n }\n return def;\n}\n\nexport function getDtypeArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: DataType[]): DataType[] {\n const param = attrs[name];\n if (param && param.list && param.list.type) {\n return param.list.type.map(v => parseDtypeParam(v));\n }\n return def;\n}\n\nexport function parseTensorShapeParam(shape: tensorflow.ITensorShape): number[]|\n undefined {\n if (shape.unknownRank) {\n return undefined;\n }\n if (shape.dim != null) {\n return shape.dim.map(\n dim =>\n (typeof dim.size === 'number') ? dim.size : parseInt(dim.size, 10));\n }\n return [];\n}\n\nexport function getTensorShapeParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def?: number[]): number[]|undefined {\n const param = attrs[name];\n if (param && param.shape) {\n return parseTensorShapeParam(param.shape);\n }\n return def;\n}\n\nexport function getNumericArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number[]): number[] {\n const param = attrs[name];\n if (param) {\n return ((param.list.f && param.list.f.length ? param.list.f :\n param.list.i) ||\n [])\n .map(v => (typeof v === 'number') ? v : parseInt(v, 10));\n }\n return def;\n}\n\nexport function getStringArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string[],\n keepCase = false): string[] {\n const param = attrs[name];\n if (param && param.list && param.list.s) {\n return param.list.s.map((v) => {\n return parseStringParam(v, keepCase);\n });\n }\n return def;\n}\n\nexport function getTensorShapeArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number[][]): number[][] {\n const param = attrs[name];\n if (param && param.list && param.list.shape) {\n return param.list.shape.map((v) => {\n return parseTensorShapeParam(v);\n });\n }\n return def;\n}\n\nexport function getBoolArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: boolean[]): boolean[] {\n const param = attrs[name];\n if (param && param.list && param.list.b) {\n return param.list.b;\n }\n return def;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {getTensor} from '../executors/utils';\nimport {getBoolArrayParam, getBoolParam, getDtypeArrayParam, getDtypeParam, getNumberParam, getNumericArrayParam, getStringArrayParam, getStringParam, getTensorShapeArrayParam, getTensorShapeParam} from '../operation_mapper';\nimport {GraphNode, Node, ValueType} from '../types';\n\n/**\n * Helper class for lookup inputs and params for nodes in the model graph.\n */\nexport class NodeValueImpl implements GraphNode {\n public readonly inputs: Tensor[] = [];\n public readonly attrs: {[key: string]: ValueType} = {};\n constructor(\n private node: Node, private tensorMap: NamedTensorsMap,\n private context: ExecutionContext) {\n this.inputs = node.inputNames.map(name => this.getInput(name));\n if (node.rawAttrs != null) {\n this.attrs = Object.keys(node.rawAttrs)\n .reduce((attrs: {[key: string]: ValueType}, key) => {\n attrs[key] = this.getAttr(key);\n return attrs;\n }, {});\n }\n }\n\n /**\n * Return the value of the attribute or input param.\n * @param name String: name of attribute or input param.\n */\n private getInput(name: string): Tensor {\n return getTensor(name, this.tensorMap, this.context);\n }\n\n /**\n * Return the value of the attribute or input param.\n * @param name String: name of attribute or input param.\n */\n private getAttr(name: string, defaultValue?: ValueType): ValueType {\n const value = this.node.rawAttrs[name];\n if (value.tensor != null) {\n return getTensor(name, this.tensorMap, this.context);\n }\n if (value.i != null || value.f != null) {\n return getNumberParam(this.node.rawAttrs, name, defaultValue as number);\n }\n if (value.s != null) {\n return getStringParam(this.node.rawAttrs, name, defaultValue as string);\n }\n if (value.b != null) {\n return getBoolParam(this.node.rawAttrs, name, defaultValue as boolean);\n }\n if (value.shape != null) {\n return getTensorShapeParam(\n this.node.rawAttrs, name, defaultValue as number[]);\n }\n if (value.type != null) {\n return getDtypeParam(this.node.rawAttrs, name, defaultValue as DataType);\n }\n if (value.list != null) {\n if (value.list.i != null || value.list.f != null) {\n return getNumericArrayParam(\n this.node.rawAttrs, name, defaultValue as number[]);\n }\n if (value.list.s != null) {\n return getStringArrayParam(\n this.node.rawAttrs, name, defaultValue as string[]);\n }\n if (value.list.shape != null) {\n return getTensorShapeArrayParam(\n this.node.rawAttrs, name, defaultValue as number[][]);\n }\n if (value.list.b != null) {\n return getBoolArrayParam(\n this.node.rawAttrs, name, defaultValue as boolean[]);\n }\n if (value.list.type != null) {\n return getDtypeArrayParam(\n this.node.rawAttrs, name, defaultValue as DataType[]);\n }\n }\n\n return defaultValue;\n }\n}\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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) {\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) {\n this.tensors.forEach(tensor => {\n if (keepIds == null || !keepIds.has(tensor.id)) {\n tensor.dispose();\n }\n });\n this.tensors.length = 0;\n this.idTensor.dispose();\n }\n /**\n * The size of the tensors in the tensor list.\n */\n size() {\n return this.tensors.length;\n }\n\n /**\n * Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)\n * tf.Tensor.\n * @param elementShape shape of each tensor\n * @param elementDtype data type of each tensor\n * @param numElements the number of elements to stack\n */\n stack(elementShape: number[], elementDtype: DataType, numElements = -1):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n if (numElements !== -1 && this.tensors.length !== numElements) {\n throw new Error(`Operation expected a list with ${\n numElements} elements but got a list with ${\n this.tensors.length} elements.`);\n }\n assertShapesMatchAllowUndefinedSize(\n elementShape, this.elementShape, 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n return tidy(() => {\n const reshapedTensors =\n this.tensors.map(tensor => reshape(tensor, outputElementShape));\n return stack(reshapedTensors, 0);\n });\n }\n\n /**\n * Pop a tensor from the end of the list.\n * @param elementShape shape of the tensor\n * @param elementDtype data type of the tensor\n */\n popBack(elementShape: number[], elementDtype: DataType): Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n\n if (this.size() === 0) {\n throw new Error('Trying to pop from an empty list.');\n }\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n const tensor = this.tensors.pop();\n tensor.kept = false;\n\n assertShapesMatchAllowUndefinedSize(\n tensor.shape, elementShape, 'TensorList shape mismatch: ');\n\n return reshape(tensor, outputElementShape);\n }\n\n /**\n * Push a tensor to the end of the list.\n * @param tensor Tensor to be pushed.\n */\n pushBack(tensor: Tensor) {\n if (tensor.dtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${this.elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n tensor.shape, this.elementShape, 'TensorList shape mismatch: ');\n\n if (this.maxNumElements === this.size()) {\n throw new Error(`Trying to push element into a full list.`);\n }\n keep(tensor);\n this.tensors.push(tensor);\n }\n\n /**\n * Update the size of the list.\n * @param size the new size of the list.\n */\n resize(size: number) {\n if (size < 0) {\n throw new Error(\n `TensorListResize expects size to be non-negative. Got: ${size}`);\n }\n\n if (this.maxNumElements !== -1 && size > this.maxNumElements) {\n throw new Error(`TensorListResize input size ${\n size} is greater maxNumElement ${this.maxNumElements}.`);\n }\n\n const destTensorList: TensorList = new TensorList(\n [], this.elementShape, this.elementDtype, this.maxNumElements);\n destTensorList.tensors.length = size;\n for (let i = 0; i < Math.min(this.tensors.length, size); ++i) {\n destTensorList.tensors[i] = this.tensors[i];\n }\n return destTensorList;\n }\n\n /**\n * Retrieve the element at the provided index\n * @param elementShape shape of the tensor\n * @param elementDtype dtype of the tensor\n * @param elementIndex index of the tensor\n */\n getItem(elementIndex: number, elementShape: number[], elementDtype: DataType):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n if (elementIndex < 0 || elementIndex > this.tensors.length) {\n throw new Error(`Trying to access element ${\n elementIndex} in a list with ${this.tensors.length} elements.`);\n }\n\n if (this.tensors[elementIndex] == null) {\n throw new Error(`element at index ${elementIndex} is null.`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.tensors[elementIndex].shape, elementShape,\n 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n return reshape(this.tensors[elementIndex], outputElementShape);\n }\n\n /**\n * Set the tensor at the index\n * @param elementIndex index of the tensor\n * @param tensor the tensor to be inserted into the list\n */\n setItem(elementIndex: number, tensor: Tensor) {\n if (tensor.dtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${this.elementDtype}`);\n }\n\n if (elementIndex < 0 ||\n this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {\n throw new Error(`Trying to set element ${\n elementIndex} in a list with max ${this.maxNumElements} elements.`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, tensor.shape, 'TensorList shape mismatch: ');\n keep(tensor);\n\n // dispose the previous value if it is replacing.\n if (this.tensors[elementIndex] != null) {\n this.tensors[elementIndex].kept = false;\n }\n\n this.tensors[elementIndex] = tensor;\n }\n\n /**\n * Return selected values in the TensorList as a stacked Tensor. All of\n * selected values must have been written and their shapes must all match.\n * @param indices indices of tensors to gather\n * @param elementDtype output tensor dtype\n * @param elementShape output tensor element shape\n */\n gather(indices: number[], elementDtype: DataType, elementShape: number[]):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, elementShape, 'TensorList shape mismatch: ');\n\n // When indices is greater than the size of the list, indices beyond the\n // size of the list are ignored.\n indices = indices.slice(0, this.size());\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n if (indices.length === 0) {\n return tensor([], [0].concat(outputElementShape));\n }\n\n return tidy(() => {\n const tensors =\n indices.map(i => reshape(this.tensors[i], outputElementShape));\n return stack(tensors, 0);\n });\n }\n\n /**\n * Return the values in the TensorList as a concatenated Tensor.\n * @param elementDtype output tensor dtype\n * @param elementShape output tensor element shape\n */\n concat(elementDtype: DataType, elementShape: number[]): Tensor {\n if (!!elementDtype && elementDtype !== this.elementDtype) {\n throw new Error(`TensorList dtype is ${\n this.elementDtype} but concat requested dtype ${elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, elementShape, 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n\n if (this.size() === 0) {\n return tensor([], [0].concat(outputElementShape));\n }\n return tidy(() => {\n const tensors = this.tensors.map(t => reshape(t, outputElementShape));\n return concat(tensors, 0);\n });\n }\n}\n\n/**\n * Creates a TensorList which, when stacked, has the value of tensor.\n * @param tensor from tensor\n * @param elementShape output tensor element shape\n */\nexport function fromTensor(\n tensor: Tensor, elementShape: number[], elementDtype: DataType) {\n const dtype = tensor.dtype;\n if (tensor.shape.length < 1) {\n throw new Error(\n `Tensor must be at least a vector, but saw shape: ${tensor.shape}`);\n }\n if (tensor.dtype !== elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${elementDtype}`);\n }\n const tensorElementShape = tensor.shape.slice(1);\n assertShapesMatchAllowUndefinedSize(\n tensorElementShape, elementShape, 'TensorList shape mismatch: ');\n const tensorList: Tensor[] = unstack(tensor);\n return new TensorList(tensorList, elementShape, dtype);\n}\n\n/**\n * Return a TensorList of the given size with empty elements.\n * @param elementShape the shape of the future elements of the list\n * @param elementDtype the desired type of elements in the list\n * @param numElements the number of elements to reserve\n * @param maxNumElements the maximum number of elements in th list\n */\nexport function reserve(\n elementShape: number[], elementDtype: DataType, numElements: number,\n maxNumElements: number) {\n return new TensorList([], elementShape, elementDtype, maxNumElements);\n}\n\n/**\n * Put tensors at specific indices of a stacked tensor into a TensorList.\n * @param indices list of indices on how to scatter the tensor.\n * @param tensor input tensor.\n * @param elementShape the shape of the future elements of the list\n * @param numElements the number of elements to scatter\n */\nexport function scatter(\n tensor: Tensor, indices: number[], elementShape: number[],\n numElements?: number): TensorList {\n if (indices.length !== tensor.shape[0]) {\n throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${\n indices.length} vs. ${tensor.shape[0]}`);\n }\n\n const maxIndex = Math.max(...indices);\n\n if (numElements != null && numElements !== -1 && maxIndex >= numElements) {\n throw new Error(\n `Max index must be < array size (${maxIndex} vs. ${numElements})`);\n }\n\n const list = new TensorList([], elementShape, tensor.dtype, numElements);\n const tensors = unstack(tensor, 0);\n indices.forEach((value, index) => {\n list.setItem(value, tensors[index]);\n });\n return list;\n}\n\n/**\n * Split the values of a Tensor into a TensorList.\n * @param length the lengths to use when splitting value along\n * its first dimension.\n * @param tensor the tensor to split.\n * @param elementShape the shape of the future elements of the list\n */\nexport function split(\n tensor: Tensor, length: number[], elementShape: number[]) {\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n\n const shapeWithoutFirstDim = tensor.shape.slice(1);\n const outputElementShape =\n mergeElementShape(shapeWithoutFirstDim, elementShape);\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors: Tensor[] = tidy(() => {\n const tensors = [];\n tensor = reshape(tensor, [1, totalLength, elementPerRow]);\n for (let i = 0; i < length.length; ++i) {\n const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = reshape(\n slice(tensor, indices, sizes), outputElementShape as number[]);\n }\n tensor.dispose();\n return tensors;\n });\n\n const list = new TensorList([], elementShape, tensor.dtype, length.length);\n\n for (let i = 0; i < tensors.length; i++) {\n list.setItem(i, tensors[i]);\n }\n return list;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, scalar, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {TensorArray} from '../../executor/tensor_array';\nimport {fromTensor, reserve, scatter, split} from '../../executor/tensor_list';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Promise => {\n switch (node.op) {\n case 'If':\n case 'StatelessIf': {\n const thenFunc =\n getParamValue('thenBranch', node, tensorMap, context) as string;\n const elseFunc =\n getParamValue('elseBranch', node, tensorMap, context) as string;\n const cond = getParamValue('cond', node, tensorMap, context) as Tensor;\n const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n const condValue = await cond.data();\n if (condValue[0]) {\n return context.functionMap[thenFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap);\n } else {\n return context.functionMap[elseFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap);\n }\n }\n case 'While':\n case 'StatelessWhile': {\n const bodyFunc =\n getParamValue('body', node, tensorMap, context) as string;\n const condFunc =\n getParamValue('cond', node, tensorMap, context) as string;\n const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n\n // Calculate the condition of the loop\n const condResult =\n (await context.functionMap[condFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap));\n const argIds = args.map(tensor => tensor.id);\n let condValue = await condResult[0].data();\n // Dispose the intermediate tensors for condition function\n condResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n\n let result: Tensor[] = args;\n\n while (condValue[0]) {\n // Record the previous result for intermediate tensor tracking\n const origResult = result;\n // Execution the body of the loop\n result = await context.functionMap[bodyFunc].executeFunctionAsync(\n result, context.tensorArrayMap, context.tensorListMap);\n const resultIds = result.map(tensor => tensor.id);\n\n // Dispose the intermediate tensor for body function that is not global\n // kept, not input/output of the body function\n origResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n resultIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n\n // Recalcuate the condition of the loop using the latest results.\n const condResult =\n (await context.functionMap[condFunc].executeFunctionAsync(\n result, context.tensorArrayMap, context.tensorListMap));\n condValue = await condResult[0].data();\n // Dispose the intermediate tensors for condition function\n condResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n resultIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n }\n return result;\n }\n case 'LoopCond': {\n const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n return [cloneTensor(pred)];\n }\n case 'Switch': {\n const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n let data = getParamValue('data', node, tensorMap, context) as Tensor;\n if (!data.kept) {\n data = cloneTensor(data);\n }\n // Outputs nodes :0 => false, :1 => true\n return (await pred.data())[0] ? [undefined, data] : [data, undefined];\n }\n case 'Merge': {\n const inputName = node.inputNames.find(\n name => getTensor(name, tensorMap, context) !== undefined);\n if (inputName) {\n const data = getTensor(inputName, tensorMap, context);\n return [cloneTensor(data)];\n }\n return undefined;\n }\n case 'Enter': {\n const frameId =\n getParamValue('frameName', node, tensorMap, context) as string;\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.enterFrame(frameId);\n return [cloneTensor(data)];\n }\n case 'Exit': {\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.exitFrame();\n return [cloneTensor(data)];\n }\n case 'NextIteration': {\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.nextIteration();\n return [cloneTensor(data)];\n }\n case 'TensorArrayV3': {\n const size = getParamValue('size', node, tensorMap, context) as number;\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const dynamicSize =\n getParamValue('dynamicSize', node, tensorMap, context) as boolean;\n const clearAfterRead =\n getParamValue('clearAfterRead', node, tensorMap, context) as boolean;\n const identicalElementShapes =\n getParamValue('identicalElementShapes', node, tensorMap, context) as\n boolean;\n const name = getParamValue('name', node, tensorMap, context) as string;\n const tensorArray = new TensorArray(\n name, dtype, size, elementShape, identicalElementShapes, dynamicSize,\n clearAfterRead);\n context.addTensorArray(tensorArray);\n return [tensorArray.idTensor, scalar(1.0)];\n }\n case 'TensorArrayWriteV3': {\n const id =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const index = getParamValue('index', node, tensorMap, context) as number;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const writeTensorArray = context.getTensorArray(id.id);\n writeTensorArray.write(index, writeTensor);\n return [writeTensorArray.idTensor];\n }\n case 'TensorArrayReadV3': {\n const readId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const readIndex =\n getParamValue('index', node, tensorMap, context) as number;\n const readTensorArray = context.getTensorArray(readId.id);\n return [readTensorArray.read(readIndex)];\n }\n case 'TensorArrayGatherV3': {\n const gatherId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const gatherIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const gatherDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const gatherTensorArray = context.getTensorArray(gatherId.id);\n return [gatherTensorArray.gather(gatherIndices, gatherDtype)];\n }\n case 'TensorArrayScatterV3': {\n const scatterId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const scatterIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const scatterTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const scatterTensorArray = context.getTensorArray(scatterId.id);\n scatterTensorArray.scatter(scatterIndices, scatterTensor);\n return [scatterTensorArray.idTensor];\n }\n case 'TensorArrayConcatV3': {\n const concatId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const concatTensorArray = context.getTensorArray(concatId.id);\n const concatDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n return [concatTensorArray.concat(concatDtype)];\n }\n case 'TensorArraySplitV3': {\n const splitId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const splitTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const lengths =\n getParamValue('lengths', node, tensorMap, context) as number[];\n const splitTensorArray = context.getTensorArray(splitId.id);\n splitTensorArray.split(lengths, splitTensor);\n return [splitTensorArray.idTensor];\n }\n case 'TensorArraySizeV3': {\n const sizeId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const sizeTensorArray = context.getTensorArray(sizeId.id);\n return [scalar(sizeTensorArray.size(), 'int32')];\n }\n case 'TensorArrayCloseV3': {\n const closeId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const closeTensorArray = context.getTensorArray(closeId.id);\n closeTensorArray.clearAndClose();\n return [closeTensorArray.idTensor];\n }\n case 'TensorListSetItem': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const index = getParamValue('index', node, tensorMap, context) as number;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n tensorList.setItem(index, writeTensor);\n return [tensorList.idTensor];\n }\n case 'TensorListGetItem': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const readIndex =\n getParamValue('index', node, tensorMap, context) as number;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n\n const elementDType =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.getItem(readIndex, elementShape, elementDType)];\n }\n case 'TensorListScatterV2':\n case 'TensorListScatter': {\n const scatterIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const scatterTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const numElements =\n getParamValue('numElements', node, tensorMap, context) as number;\n const tensorList =\n scatter(scatterTensor, scatterIndices, elementShape, numElements);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListReserve':\n case 'EmptyTensorList': {\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n let numElementsParam;\n\n if (node.op === 'TensorListReserve') {\n numElementsParam = 'numElements';\n } else {\n numElementsParam = 'maxNumElements';\n }\n\n const numElements =\n getParamValue(numElementsParam, node, tensorMap, context) as number;\n const maxNumElements = node.op === 'TensorListReserve' ? -1 : numElements;\n const tensorList =\n reserve(elementShape, elementDtype, numElements, maxNumElements);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListGather': {\n const gatherId =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const gatherIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(gatherId.id);\n return [tensorList.gather(gatherIndices, elementDtype, elementShape)];\n }\n case 'TensorListStack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const numElements =\n getParamValue('numElements', node, tensorMap, context) as number;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.stack(elementShape, elementDtype, numElements)];\n }\n case 'TensorListFromTensor': {\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = fromTensor(tensor, elementShape, elementDtype);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListConcat':\n case 'TensorListConcatV2': {\n const concatId =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(concatId.id);\n const concatDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n return [tensorList.concat(concatDtype, elementShape)];\n }\n case 'TensorListPushBack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n tensorList.pushBack(writeTensor);\n return [tensorList.idTensor];\n }\n case 'TensorListPopBack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDType =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.popBack(elementShape, elementDType)];\n }\n case 'TensorListSplit': {\n const splitTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const lengths =\n getParamValue('lengths', node, tensorMap, context) as number[];\n\n const tensorList = split(splitTensor, lengths, elementShape);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListLength': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n return [scalar(tensorList.size(), 'int32')];\n }\n case 'TensorListResize': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const size = getParamValue('size', node, tensorMap, context) as number;\n\n const srcTensorList = context.getTensorList(idTensor.id);\n const destTensorList = srcTensorList.resize(size);\n context.addTensorList(destTensorList);\n return [destTensorList.idTensor];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'control';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Rank, Tensor, Tensor3D, Tensor4D, Tensor5D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getPadding, getParamValue} from './utils';\n\nfunction fusedConvAndDepthWiseParams(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n const [extraOp, activationFunc] =\n (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n const isBiasAdd = extraOp === 'biasadd';\n const noBiasAdd = !isBiasAdd;\n const isPrelu = activationFunc === 'prelu';\n const isBatchNorm = extraOp === 'fusedbatchnorm';\n\n const numArgs =\n (getParamValue('numArgs', node, tensorMap, context) as number);\n if (isBiasAdd) {\n if (isPrelu && numArgs !== 2) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' +\n 'must have two extra arguments: bias and alpha.');\n }\n if (!isPrelu && isBiasAdd && numArgs !== 1) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with BiasAdd must have ' +\n 'one extra argument: bias.');\n }\n }\n if (isBatchNorm) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported');\n }\n const stride = getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n let [biasArg, preluArg] =\n getParamValue('args', node, tensorMap, context) as Tensor[];\n if (noBiasAdd) {\n preluArg = biasArg;\n biasArg = undefined;\n }\n const leakyreluAlpha =\n getParamValue('leakyreluAlpha', node, tensorMap, context) as number;\n\n return {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha\n };\n}\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Conv1D': {\n const stride =\n getParamValue('stride', node, tensorMap, context) as number;\n const pad = getParamValue('pad', node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilation =\n getParamValue('dilation', node, tensorMap, context) as number;\n return [ops.conv1d(\n getParamValue('x', node, tensorMap, context) as Tensor3D,\n getParamValue('filter', node, tensorMap, context) as Tensor3D,\n stride, pad as 'valid' | 'same', dataFormat as 'NWC' | 'NCW',\n dilation)];\n }\n case 'Conv2D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n return [ops.conv2d(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n [stride[1], stride[2]], pad as 'valid' | 'same',\n dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n }\n case '_FusedConv2D': {\n const {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha\n } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n return [ops.fused.conv2d({\n x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n filter: getParamValue('filter', node, tensorMap, context) as\n Tensor4D,\n strides: [stride[1], stride[2]],\n pad: pad as 'valid' | 'same',\n dataFormat: dataFormat as 'NHWC' | 'NCHW',\n dilations: [dilations[1], dilations[2]],\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n }\n\n case 'FusedDepthwiseConv2dNative': {\n const {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha,\n } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n return [ops.fused.depthwiseConv2d({\n x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n filter: getParamValue('filter', node, tensorMap, context) as\n Tensor4D,\n strides: [stride[1], stride[2]],\n pad: pad as 'valid' | 'same',\n dataFormat: dataFormat as 'NHWC' | 'NCHW',\n dilations: [dilations[1], dilations[2]],\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n }\n case 'Conv2DBackpropInput':\n case 'Conv2dTranspose': {\n const shape = getParamValue(\n 'outputShape', node, tensorMap,\n context) as [number, number, number] |\n [number, number, number, number];\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n return [ops.conv2dTranspose(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n shape, [stride[1], stride[2]], pad as 'valid' | 'same')];\n }\n case 'DepthwiseConv2dNative':\n case 'DepthwiseConv2d': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n\n return [ops.depthwiseConv2d(\n getParamValue('input', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n [stride[1], stride[2]], pad as 'valid' | 'same',\n dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n }\n case 'Conv3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n return [ops.conv3d(\n getParamValue('x', node, tensorMap, context) as Tensor4D |\n Tensor,\n getParamValue('filter', node, tensorMap, context) as\n Tensor,\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same',\n dataFormat as 'NDHWC' | 'NCDHW',\n [dilations[1], dilations[2], dilations[3]])];\n }\n case 'AvgPool': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.avgPool(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same')];\n }\n case 'MaxPool': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.maxPool(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same')];\n }\n case 'MaxPoolWithArgmax': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n const includeBatchInIndex =\n getParamValue('includeBatchInIndex', node, tensorMap, context) as\n boolean;\n const {result, indexes} = ops.maxPoolWithArgmax(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same', includeBatchInIndex);\n return [result, indexes];\n }\n case 'AvgPool3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.avgPool3d(\n getParamValue('x', node, tensorMap, context) as Tensor5D,\n [kernelSize[1], kernelSize[2], kernelSize[3]],\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n }\n\n case 'MaxPool3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.maxPool3d(\n getParamValue('x', node, tensorMap, context) as Tensor5D,\n [kernelSize[1], kernelSize[2], kernelSize[3]],\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n }\n\n case 'Dilation2D': {\n const strides =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n\n // strides: [1, stride_height, stride_width, 1].\n const strideHeight = strides[1];\n const strideWidth = strides[2];\n\n // dilations: [1, dilation_height, dilation_width, 1].\n const dilationHeight = dilations[1];\n const dilationWidth = dilations[2];\n\n return [ops.dilation2d(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor3D,\n [strideHeight, strideWidth], pad as 'valid' | 'same',\n [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)];\n }\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'convolution';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport { ResourceManager } from '../../executor/resource_manager';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nfunction nmsParams(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n const boxes = getParamValue('boxes', node, tensorMap, context) as Tensor;\n const scores = getParamValue('scores', node, tensorMap, context) as Tensor;\n const maxOutputSize =\n getParamValue('maxOutputSize', node, tensorMap, context) as number;\n const iouThreshold =\n getParamValue('iouThreshold', node, tensorMap, context) as number;\n const scoreThreshold =\n getParamValue('scoreThreshold', node, tensorMap, context) as number;\n const softNmsSigma =\n getParamValue('softNmsSigma', node, tensorMap, context) as number;\n\n return {\n boxes,\n scores,\n maxOutputSize,\n iouThreshold,\n scoreThreshold,\n softNmsSigma\n };\n}\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, resourceManager: ResourceManager,\n ops = tfOps): Promise => {\n switch (node.op) {\n case 'NonMaxSuppressionV5': {\n const {\n boxes,\n scores,\n maxOutputSize,\n iouThreshold,\n scoreThreshold,\n softNmsSigma\n } = nmsParams(node, tensorMap, context);\n\n const result = await ops.image.nonMaxSuppressionWithScoreAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold, softNmsSigma);\n\n return [result.selectedIndices, result.selectedScores];\n }\n case 'NonMaxSuppressionV4': {\n const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n nmsParams(node, tensorMap, context);\n\n const padToMaxOutputSize =\n getParamValue('padToMaxOutputSize', node, tensorMap, context) as\n boolean;\n\n const result = await ops.image.nonMaxSuppressionPaddedAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold, padToMaxOutputSize);\n\n return [result.selectedIndices, result.validOutputs];\n }\n case 'NonMaxSuppressionV3':\n case 'NonMaxSuppressionV2': {\n const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n nmsParams(node, tensorMap, context);\n\n return [await ops.image.nonMaxSuppressionAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold)];\n }\n case 'Where': {\n const condition = ops.cast(\n (getParamValue('condition', node, tensorMap, context) as Tensor),\n 'bool');\n const result = [await ops.whereAsync(condition)];\n condition.dispose();\n return result;\n }\n case 'ListDiff': {\n return ops.setdiff1dAsync(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor);\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'dynamic';\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;\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();\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 {\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 {\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, tidy = tfc.tidy): tfc.Tensor[]|\n Promise {\n const value =\n ((node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) => {\n switch (node.category) {\n case 'arithmetic':\n return tidy(() => arithmetic.executeOp(node, tensorMap, context));\n case 'basic_math':\n return tidy(() => basicMath.executeOp(node, tensorMap, context));\n case 'control':\n return control.executeOp(node, tensorMap, context);\n case 'convolution':\n return tidy(() => convolution.executeOp(node, tensorMap, context));\n case 'creation':\n return tidy(() => creation.executeOp(node, tensorMap, context));\n case 'dynamic':\n return dynamic.executeOp(node, tensorMap, context);\n case 'evaluation':\n return tidy(() => evaluation.executeOp(node, tensorMap, context));\n case 'image':\n return tidy(() => image.executeOp(node, tensorMap, context));\n case 'graph':\n return tidy(() => graph.executeOp(node, tensorMap, context));\n case 'logical':\n return tidy(() => logical.executeOp(node, tensorMap, context));\n case 'matrices':\n return tidy(() => matrices.executeOp(node, tensorMap, context));\n case 'normalization':\n return tidy(\n () => normalization.executeOp(node, tensorMap, context));\n case 'reduction':\n return tidy(() => reduction.executeOp(node, tensorMap, context));\n case 'slice_join':\n return tidy(() => sliceJoin.executeOp(node, tensorMap, context));\n case 'sparse':\n return tidy(() => sparse.executeOp(node, tensorMap, context));\n case 'spectral':\n return tidy(() => spectral.executeOp(node, tensorMap, context));\n case 'string':\n return tidy(() => string.executeOp(node, tensorMap, context));\n case 'transformation':\n return tidy(\n () => transformation.executeOp(node, tensorMap, context));\n case 'hash_table':\n return hashTable.executeOp(\n node, tensorMap, context, resourceManager);\n case 'custom':\n const opMapper = getRegisteredOp(node.op);\n if (opMapper && opMapper.customExecutor) {\n return opMapper.customExecutor(\n new NodeValueImpl(node, tensorMap, context));\n } else {\n throw TypeError(`Custom op ${node.op} is not registered.`);\n }\n default:\n throw TypeError(\n `Unknown op '${node.op}'. File an issue at ` +\n `https://github.com/tensorflow/tfjs/issues so we can add it` +\n `, or register a custom execution with tf.registerOp()`);\n }\n })(node, tensorMap, context);\n if (tfc.util.isPromise(value)) {\n return value.then((data) => [].concat(data));\n }\n return [].concat(value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'BiasAdd':\n case 'AddV2':\n case 'Add': {\n return [ops.add(\n (getParamValue('a', node, tensorMap, context) as Tensor),\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'AddN': {\n return [ops.addN((\n getParamValue('tensors', node, tensorMap, context) as Tensor[]))];\n }\n case 'FloorMod':\n case 'Mod':\n return [ops.mod(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'Mul':\n return [ops.mul(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'RealDiv':\n case 'Div': {\n return [ops.div(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'DivNoNan': {\n return [ops.divNoNan(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'FloorDiv': {\n return [ops.floorDiv(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Sub': {\n return [ops.sub(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Minimum': {\n return [ops.minimum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Maximum': {\n return [ops.maximum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Pow': {\n return [ops.pow(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'SquaredDifference': {\n return [ops.squaredDifference(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'arithmetic';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Abs':\n case 'ComplexAbs':\n return [ops.abs(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acos':\n return [ops.acos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acosh':\n return [ops.acosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asin':\n return [ops.asin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asinh':\n return [ops.asinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan':\n return [ops.atan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan2':\n return [ops.atan2(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor)];\n case 'Atanh':\n return [ops.atanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Ceil':\n return [ops.ceil(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Complex':\n return [ops.complex(\n getParamValue('real', node, tensorMap, context) as Tensor,\n getParamValue('imag', node, tensorMap, context) as Tensor)];\n case 'Cos':\n return [ops.cos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Cosh':\n return [ops.cosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Elu':\n return [ops.elu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Erf':\n return [ops.erf(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Exp':\n return [ops.exp(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Expm1': {\n return [ops.expm1(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Floor':\n return [ops.floor(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log':\n return [ops.log(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log1p': {\n return [ops.log1p(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Imag':\n return [ops.imag(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n\n case 'Neg':\n return [ops.neg(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Reciprocal': {\n return [ops.reciprocal(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Real':\n return [ops.real(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Relu':\n return [ops.relu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Round': {\n return [ops.round(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Selu':\n return [ops.selu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sigmoid':\n return [ops.sigmoid(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sin':\n return [ops.sin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sign': {\n return [ops.sign(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sinh': {\n return [ops.sinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Softplus': {\n return [ops.softplus(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sqrt': {\n return [ops.sqrt(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Square': {\n return [ops.square(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tanh': {\n return [ops.tanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tan':\n return [ops.tan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'ClipByValue':\n return [ops.clipByValue(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('clipValueMin', node, tensorMap, context) as number,\n getParamValue('clipValueMax', node, tensorMap, context) as\n number)];\n case 'Relu6':\n return [ops.relu6(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Rsqrt':\n return [ops.rsqrt(\n getTensor(node.inputNames[0], tensorMap, context))];\n case 'Prod':\n return [ops.prod(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('axes', node, tensorMap, context) as number[])];\n case 'LeakyRelu':\n return [ops.leakyRelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as number)];\n case 'Prelu':\n return [ops.prelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as Tensor)];\n case 'IsNan':\n return [ops.isNaN(\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, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Fill': {\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const value =\n getParamValue('value', node, tensorMap, context) as number;\n return [ops.fill(shape, value, dtype)];\n }\n case 'LinSpace': {\n const start =\n getParamValue('start', node, tensorMap, context) as number;\n const stop =\n getParamValue('stop', node, tensorMap, context) as number;\n const num = getParamValue('num', node, tensorMap, context) as number;\n return [ops.linspace(start, stop, num)];\n }\n case 'Multinomial': {\n const logits =\n getParamValue('logits', node, tensorMap, context) as Tensor1D;\n const numSamples =\n getParamValue('numSamples', node, tensorMap, context) as number;\n const seed =\n getParamValue('seed', node, tensorMap, context) as number;\n return [ops.multinomial(logits, numSamples, seed)];\n }\n case 'OneHot': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n const depth =\n getParamValue('depth', node, tensorMap, context) as number;\n const onValue =\n getParamValue('onValue', node, tensorMap, context) as number;\n const offValue =\n getParamValue('offValue', node, tensorMap, context) as number;\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n return [ops.oneHot(indices, depth, onValue, offValue, dtype)];\n }\n case 'Ones': {\n return [ops.ones(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'OnesLike': {\n return [ops.onesLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RandomStandardNormal': {\n return [ops.randomStandardNormal(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32',\n getParamValue('seed', node, tensorMap, context) as number)];\n }\n case 'RandomUniform': {\n return [ops.randomUniform(\n // tslint:disable-next-line:no-any\n getParamValue('shape', node, tensorMap, context) as any,\n getParamValue('minval', node, tensorMap, context) as number,\n getParamValue('maxval', node, tensorMap, context) as number,\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'Range': {\n const start =\n getParamValue('start', node, tensorMap, context) as number;\n const stop =\n getParamValue('stop', node, tensorMap, context) as number;\n const step =\n getParamValue('step', node, tensorMap, context) as number;\n return [ops.range(\n start, stop, step,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32')];\n }\n case 'TruncatedNormal': {\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n const mean =\n getParamValue('mean', node, tensorMap, context) as number;\n const stdDev =\n getParamValue('stdDev', node, tensorMap, context) as number;\n const seed =\n getParamValue('seed', node, tensorMap, context) as number;\n return [ops.truncatedNormal(\n shape, mean, stdDev,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32',\n seed)];\n }\n case 'Zeros': {\n return [ops.zeros(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'ZerosLike': {\n return [ops.zerosLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'creation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps):\n Tensor[] => {\n switch (node.op) {\n case 'LowerBound': {\n const sortedSequence =\n getParamValue('sortedSequence', node, tensorMap, context) as\n Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n return [ops.lowerBound(sortedSequence, values)];\n }\n case 'TopKV2': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const k = getParamValue('k', node, tensorMap, context) as number;\n const sorted =\n getParamValue('sorted', node, tensorMap, context) as boolean;\n const result = ops.topk(x, k, sorted);\n return [result.values, result.indices];\n }\n case 'UpperBound': {\n const sortedSequence =\n getParamValue('sortedSequence', node, tensorMap, context) as\n Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n return [ops.upperBound(sortedSequence, values)];\n }\n case 'Unique': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const result = ops.unique(x);\n return [result.values, result.indices];\n }\n case 'UniqueV2': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const result = ops.unique(x, axis);\n return [result.values, result.indices];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'evaluation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'ResizeBilinear': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const size =\n getParamValue('size', node, tensorMap, context) as number[];\n const alignCorners =\n getParamValue('alignCorners', node, tensorMap, context) as\n boolean;\n const halfPixelCenters =\n getParamValue('halfPixelCenters', node, tensorMap, context) as\n boolean;\n return [ops.image.resizeBilinear(\n images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n halfPixelCenters)];\n }\n case 'ResizeNearestNeighbor': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const size =\n getParamValue('size', node, tensorMap, context) as number[];\n const alignCorners =\n getParamValue('alignCorners', node, tensorMap, context) as\n boolean;\n const halfPixelCenters =\n getParamValue('halfPixelCenters', node, tensorMap, context) as\n boolean;\n return [ops.image.resizeNearestNeighbor(\n images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n halfPixelCenters)];\n }\n case 'CropAndResize': {\n const image =\n getParamValue('image', node, tensorMap, context) as Tensor;\n const boxes =\n getParamValue('boxes', node, tensorMap, context) as Tensor;\n const boxInd =\n getParamValue('boxInd', node, tensorMap, context) as Tensor;\n const cropSize =\n getParamValue('cropSize', node, tensorMap, context) as number[];\n const method =\n getParamValue('method', node, tensorMap, context) as string;\n const extrapolationValue =\n getParamValue('extrapolationValue', node, tensorMap, context) as\n number;\n return [ops.image.cropAndResize(\n image as Tensor4D, boxes as Tensor2D, boxInd as Tensor1D,\n cropSize as [number, number], method as 'bilinear' | 'nearest',\n extrapolationValue)];\n }\n case 'ImageProjectiveTransformV3': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const transforms =\n getParamValue('transforms', node, tensorMap, context) as Tensor;\n const outputShape =\n getParamValue('outputShape', node, tensorMap, context) as\n number[];\n const fillValue =\n getParamValue('fillValue', node, tensorMap, context) as number;\n const interpolation =\n getParamValue('interpolation', node, tensorMap, context) as\n string;\n const fillMode =\n getParamValue('fillMode', node, tensorMap, context) as string;\n return [ops.image.transform(\n images as Tensor4D,\n transforms as Tensor2D,\n interpolation.toLowerCase() as 'bilinear' | 'nearest',\n fillMode.toLowerCase() as 'constant' | 'reflect' | 'wrap' | 'nearest',\n fillValue,\n outputShape as [number, number])];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'image';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Const': {\n return tensorMap[node.name];\n }\n case 'PlaceholderWithDefault':\n const def =\n getParamValue('default', node, tensorMap, context) as Tensor;\n return [getTensor(node.name, tensorMap, context) || def];\n case 'Placeholder':\n return [getTensor(node.name, tensorMap, context)];\n case 'Identity':\n case 'StopGradient':\n case 'FakeQuantWithMinMaxVars': { // This op is currently ignored.\n const data = getParamValue('x', node, tensorMap, context) as Tensor;\n return [cloneTensor(data)];\n }\n case 'IdentityN':\n return (getParamValue('x', node, tensorMap, context) as Tensor[])\n .map((t: Tensor) => cloneTensor(t));\n case 'Snapshot':\n const snapshot =\n (getParamValue('x', node, tensorMap, context) as Tensor);\n return [cloneTensor(snapshot)];\n case 'Shape':\n return [ops.tensor1d(\n (getParamValue('x', node, tensorMap, context) as Tensor).shape,\n 'int32')];\n case 'ShapeN':\n return (getParamValue('x', node, tensorMap, context) as Tensor[])\n .map((t: Tensor) => ops.tensor1d(t.shape));\n case 'Size':\n return [ops.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).size,\n 'int32')];\n case 'Rank':\n return [ops.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).rank,\n 'int32')];\n case 'NoOp':\n return [ops.scalar(1)];\n case 'Print':\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const data =\n getParamValue('data', node, tensorMap, context) as Tensor[];\n const message =\n getParamValue('message', node, tensorMap, context) as string;\n const summarize =\n getParamValue('summarize', node, tensorMap, context) as number;\n console.warn(\n 'The graph has a tf.print() operation,' +\n 'usually used for debugging, which slows down performance.');\n console.log(message);\n for (let i = 0; i < data.length; i++) {\n console.log(Array.prototype.slice.call(data[i].dataSync())\n .slice(0, summarize));\n }\n return [input];\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'graph';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Equal': {\n return [ops.equal(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'NotEqual': {\n return [ops.notEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Greater': {\n return [ops.greater(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'GreaterEqual': {\n return [ops.greaterEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Less': {\n return [ops.less(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LessEqual': {\n return [ops.lessEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalAnd': {\n return [ops.logicalAnd(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalNot': {\n return [ops.logicalNot(\n getParamValue('a', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalOr': {\n return [ops.logicalOr(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Select':\n case 'SelectV2': {\n return [ops.where(\n getParamValue('condition', node, tensorMap, context) as Tensor,\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n 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, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'BatchMatMul':\n case 'BatchMatMulV2':\n case 'MatMul':\n return [ops.matMul(\n getParamValue('a', node, tensorMap, context) as Tensor2D,\n getParamValue('b', node, tensorMap, context) as Tensor2D,\n getParamValue('transposeA', node, tensorMap, context) as boolean,\n getParamValue('transposeB', node, tensorMap, context) as\n boolean)];\n\n case 'Einsum':\n return [ops.einsum(\n getParamValue('equation', node, tensorMap, context) as string,\n ...getParamValue('tensors', node, tensorMap, context) as\n Tensor[])];\n\n case 'Transpose':\n return [ops.transpose(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('perm', node, tensorMap, context) as number[])];\n\n case '_FusedMatMul':\n const [extraOp, activationFunc] =\n (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n const isBiasAdd = extraOp === 'biasadd';\n const isPrelu = activationFunc === 'prelu';\n\n const numArgs =\n (getParamValue('numArgs', node, tensorMap, context) as number);\n const leakyreluAlpha =\n getParamValue('leakyreluAlpha', node, tensorMap, context) as\n number;\n\n if (isBiasAdd) {\n if (isPrelu && numArgs !== 2) {\n throw new Error(\n 'Fused MatMul with BiasAdd and Prelu must have two ' +\n 'extra arguments: bias and alpha.');\n }\n if (!isPrelu && numArgs !== 1) {\n throw new Error(\n 'Fused MatMul with BiasAdd must have one extra argument: bias.');\n }\n }\n const [biasArg, preluArg] =\n getParamValue('args', node, tensorMap, context) as Tensor[];\n return [ops.fused.matMul({\n a: getParamValue('a', node, tensorMap, context) as Tensor2D,\n b: getParamValue('b', node, tensorMap, context) as Tensor2D,\n transposeA: getParamValue('transposeA', node, tensorMap, context) as\n boolean,\n transposeB: getParamValue('transposeB', node, tensorMap, context) as\n boolean,\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n\n 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, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'EuclideanNorm':\n return [ops.euclideanNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('axis', node, tensorMap, context) as number[],\n getParamValue('keepDims', node, tensorMap, context) as boolean)];\n case 'FusedBatchNorm':\n case 'FusedBatchNormV2': {\n return [ops.batchNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('mean', node, tensorMap, context) as Tensor,\n getParamValue('variance', node, tensorMap, context) as Tensor,\n getParamValue('offset', node, tensorMap, context) as Tensor,\n getParamValue('scale', node, tensorMap, context) as Tensor,\n getParamValue('epsilon', node, tensorMap, context) as number)];\n }\n case 'FusedBatchNormV3': {\n return [ops.batchNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('mean', node, tensorMap, context) as Tensor,\n getParamValue('variance', node, tensorMap, context) as Tensor,\n getParamValue('offset', node, tensorMap, context) as Tensor,\n getParamValue('scale', node, tensorMap, context) as Tensor,\n getParamValue('epsilon', node, tensorMap, context) as number)];\n }\n case 'LRN': {\n return [ops.localResponseNormalization(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('radius', node, tensorMap, context) as number,\n getParamValue('bias', node, tensorMap, context) as number,\n getParamValue('alpha', node, tensorMap, context) as number,\n getParamValue('beta', node, tensorMap, context) as number)];\n }\n case 'Softmax': {\n return [ops.softmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'LogSoftmax': {\n return [ops.logSoftmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'SparseToDense': {\n return [ops.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, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Max': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.max(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Mean': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.mean(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Min': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.min(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Sum': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.sum(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'All': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.all(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Any': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.any(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'ArgMax': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [ops.argMax(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'ArgMin': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [ops.argMin(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'Prod': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.prod(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Cumprod': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const exclusive =\n getParamValue('exclusive', node, tensorMap, context) as boolean;\n const reverse =\n getParamValue('reverse', node, tensorMap, context) as boolean;\n return [ops.cumprod(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n exclusive, reverse)];\n }\n case 'Cumsum': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const exclusive =\n getParamValue('exclusive', node, tensorMap, context) as boolean;\n const reverse =\n getParamValue('reverse', node, tensorMap, context) as boolean;\n return [ops.cumsum(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n exclusive, reverse)];\n }\n case 'Bincount':\n const x = getParamValue('x', node, tensorMap, context) as Tensor1D;\n const weights =\n getParamValue('weights', node, tensorMap, context) as Tensor1D;\n const size =\n getParamValue('size', node, tensorMap, context) as number;\n\n return [ops.bincount(x, weights, size)];\n case 'DenseBincount': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor1D |\n Tensor2D;\n const weights =\n getParamValue('weights', node, tensorMap, context) as Tensor1D |\n Tensor2D;\n const size =\n getParamValue('size', node, tensorMap, context) as number;\n\n const binaryOutput =\n getParamValue('binaryOutput', node, tensorMap, context) as\n boolean;\n\n return [ops.denseBincount(x, weights, size, binaryOutput)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'reduction';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, tidy, util} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'ConcatV2':\n case 'Concat': {\n const n = getParamValue('n', node, tensorMap, context) as number;\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n let inputs =\n getParamValue('tensors', node, tensorMap, context) as Tensor[];\n inputs = inputs.slice(0, n);\n return [ops.concat(inputs, axis)];\n }\n case 'Gather': {\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n return [ops.gather(input, ops.cast(indices, 'int32'), 0)];\n }\n case 'GatherV2': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const batchDims =\n getParamValue('batchDims', node, tensorMap, context) as number;\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n return [ops.gather(\n input, ops.cast(indices, 'int32'), axis, batchDims)];\n }\n case 'Reverse': {\n const dims =\n getParamValue('dims', node, tensorMap, context) as boolean[];\n const axis = [];\n for (let i = 0; i < dims.length; i++) {\n if (dims[i]) {\n axis.push(i);\n }\n }\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n return [ops.reverse(input, axis)];\n }\n case 'ReverseV2': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n return [ops.reverse(input, axis)];\n }\n case 'Slice': {\n // tslint:disable-next-line:no-any\n const begin = getParamValue('begin', node, tensorMap, context) as any;\n // tslint:disable-next-line:no-any\n const size = getParamValue('size', node, tensorMap, context) as any;\n return [ops.slice(\n getParamValue('x', node, tensorMap, context) as Tensor, begin,\n size)];\n }\n case 'StridedSlice': {\n const begin =\n getParamValue('begin', node, tensorMap, context) as number[];\n const end =\n getParamValue('end', node, tensorMap, context) as number[];\n const strides =\n getParamValue('strides', node, tensorMap, context) as number[];\n const beginMask =\n getParamValue('beginMask', node, tensorMap, context) as number;\n const endMask =\n getParamValue('endMask', node, tensorMap, context) as number;\n const ellipsisMask =\n getParamValue('ellipsisMask', node, tensorMap, context) as number;\n const newAxisMask =\n getParamValue('newAxisMask', node, tensorMap, context) as number;\n const shrinkAxisMask =\n getParamValue('shrinkAxisMask', node, tensorMap, context) as\n number;\n const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n return [ops.stridedSlice(\n tensor, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask)];\n }\n case 'Pack': {\n return tidy(() => {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const tensors =\n getParamValue('tensors', node, tensorMap, context) as Tensor[];\n // Reshape the tensors to the first tensor's shape if they don't\n // match.\n const shape = tensors[0].shape;\n const squeezedShape = ops.squeeze(tensors[0]).shape;\n const mapped = tensors.map(tensor => {\n const sameShape = util.arraysEqual(tensor.shape, shape);\n if (!sameShape &&\n !util.arraysEqual(\n ops.squeeze(tensor).shape, squeezedShape)) {\n throw new Error('the input tensors shape does not match');\n }\n return sameShape ? tensor : ops.reshape(tensor, shape);\n });\n return [ops.stack(mapped, axis)];\n });\n }\n case 'Unpack': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n return ops.unstack(tensor, axis);\n }\n case 'Tile': {\n const reps =\n getParamValue('reps', node, tensorMap, context) as number[];\n return [ops.tile(\n getParamValue('x', node, tensorMap, context) as Tensor, reps)];\n }\n case 'Split':\n case 'SplitV': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const numOrSizeSplits =\n getParamValue('numOrSizeSplits', node, tensorMap, context) as\n number |\n number[];\n const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n return ops.split(tensor, numOrSizeSplits, axis);\n }\n case 'ScatterNd': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n return [ops.scatterND(indices, values, shape)];\n }\n case 'GatherNd': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n return [ops.gatherND(x, indices)];\n }\n case 'SparseToDense': {\n const indices =\n getParamValue('sparseIndices', node, tensorMap, context) as\n Tensor;\n const shape =\n getParamValue('outputShape', node, tensorMap, context) as\n number[];\n const sparseValues =\n getParamValue('sparseValues', node, tensorMap, context) as Tensor;\n const defaultValue =\n getParamValue('defaultValue', node, tensorMap, context) as Scalar;\n return [ops.sparseToDense(\n indices, sparseValues, shape,\n sparseValues.dtype === defaultValue.dtype ?\n defaultValue :\n ops.cast(defaultValue, sparseValues.dtype))];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'slice_join';\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'SparseFillEmptyRows': {\n const {\n outputIndices,\n outputValues,\n emptyRowIndicator,\n reverseIndexMap\n } =\n ops.sparse.sparseFillEmptyRows(\n getParamValue('indices', node, tensorMap, context) as\n Tensor2D,\n getParamValue('values', node, tensorMap, context) as Tensor1D,\n getParamValue('denseShape', node, tensorMap, context) as\n Tensor1D,\n getParamValue('defaultValue', node, tensorMap, context) as\n Scalar);\n return [\n outputIndices, outputValues, emptyRowIndicator, reverseIndexMap\n ];\n }\n case 'SparseReshape': {\n const {outputIndices, outputShape} = ops.sparse.sparseReshape(\n getParamValue('inputIndices', node, tensorMap, context) as\n Tensor2D,\n getParamValue('inputShape', node, tensorMap, context) as Tensor1D,\n getParamValue('newShape', node, tensorMap, context) as Tensor1D);\n return [outputIndices, outputShape];\n }\n case 'SparseSegmentMean': {\n const outputData = ops.sparse.sparseSegmentMean(\n getParamValue('data', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor1D,\n getParamValue('segmentIds', node, tensorMap, context) as\n Tensor1D);\n return [outputData];\n }\n case 'SparseSegmentSum': {\n const outputData = ops.sparse.sparseSegmentSum(\n getParamValue('data', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor1D,\n getParamValue('segmentIds', node, tensorMap, context) as\n Tensor1D);\n return [outputData];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'sparse';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'FFT': {\n return [ops.fft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IFFT': {\n return [ops.ifft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RFFT': {\n return [ops.rfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IRFFT': {\n return [ops.irfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'spectral';\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'StringNGrams': {\n const {nGrams, nGramsSplits} = ops.string.stringNGrams(\n getParamValue('data', node, tensorMap, context) as Tensor1D,\n getParamValue('dataSplits', node, tensorMap, context) as Tensor,\n getParamValue('separator', node, tensorMap, context) as string,\n getParamValue('nGramWidths', node, tensorMap, context) as\n number[],\n getParamValue('leftPad', node, tensorMap, context) as string,\n getParamValue('rightPad', node, tensorMap, context) as string,\n getParamValue('padWidth', node, tensorMap, context) as number,\n getParamValue(\n 'preserveShortSequences', node, tensorMap, context) as\n boolean);\n return [nGrams, nGramsSplits];\n }\n case 'StringSplit': {\n const {indices, values, shape} = ops.string.stringSplit(\n getParamValue('input', node, tensorMap, context) as Tensor1D,\n getParamValue('delimiter', node, tensorMap, context) as Scalar,\n getParamValue('skipEmpty', node, tensorMap, context) as boolean);\n return [indices, values, shape];\n }\n case 'StringToHashBucketFast': {\n const output = ops.string.stringToHashBucketFast(\n getParamValue('input', node, tensorMap, context) as Tensor,\n getParamValue('numBuckets', node, tensorMap, context) as number);\n return [output];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'string';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Cast': {\n return [ops.cast(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('dtype', node, tensorMap, context) as 'int32' |\n 'float32' | 'bool')];\n }\n case 'ExpandDims': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [ops.expandDims(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'Squeeze': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n return [ops.squeeze(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n\n case 'Reshape': {\n return [ops.reshape(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'MirrorPad': {\n return [ops.mirrorPad(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('padding', node, tensorMap, context) as\n Array<[number, number]>,\n getParamValue('mode', node, tensorMap, context) as 'reflect' |\n 'symmetric')];\n }\n case 'PadV2':\n case 'Pad': {\n return [ops.pad(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('padding', node, tensorMap, context) as\n Array<[number, number]>,\n getParamValue('constantValue', node, tensorMap, context) as\n number)];\n }\n case 'SpaceToBatchND': {\n const blockShape =\n getParamValue('blockShape', node, tensorMap, context) as number[];\n const paddings =\n getParamValue('paddings', node, tensorMap, context) as number[][];\n return [ops.spaceToBatchND(\n getParamValue('x', node, tensorMap, context) as Tensor,\n blockShape, paddings)];\n }\n case 'BatchToSpaceND': {\n const blockShape =\n getParamValue('blockShape', node, tensorMap, context) as number[];\n const crops =\n getParamValue('crops', node, tensorMap, context) as number[][];\n return [ops.batchToSpaceND(\n getParamValue('x', node, tensorMap, context) as Tensor,\n blockShape, crops)];\n }\n case 'DepthToSpace': {\n const blockSize =\n getParamValue('blockSize', node, tensorMap, context) as number;\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as\n string).toUpperCase() as 'NHWC' |\n 'NCHW';\n return [ops.depthToSpace(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n blockSize, dataFormat)];\n }\n case 'BroadcastTo': {\n return [ops.broadcastTo(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'BroadcastArgs': {\n return [ops.broadcastArgs(\n getParamValue('s0', node, tensorMap, context) as Tensor,\n getParamValue('s1', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'transformation';\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 => {\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 */\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) {\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;\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();\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();\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();\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, env, 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 = 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 private intermediateTensors: NamedTensorsMap = {};\n private keepIds: Set;\n private tensorsMap: NamedTensorsMap;\n private keepTensorForDebug = false;\n\n get weightIds(): number[] {\n return this.parent ? this.parent.weightIds : this._weightIds;\n }\n\n get functionExecutorMap(): {[key: string]: FunctionExecutor} {\n return this.parent ? this.parent.functionExecutorMap :\n this._functionExecutorMap;\n }\n\n get weightMap(): NamedTensorsMap {\n return this.parent ? this.parent.weightMap : this._weightMap;\n }\n\n set weightMap(weightMap: NamedTensorsMap) {\n const weightIds = Object.keys(weightMap).map(\n key => weightMap[key].map(tensor => tensor.id));\n this._weightIds = [].concat(...weightIds);\n this._weightMap = weightMap;\n }\n\n /**\n * Set `ResourceManager` shared by executors of a model.\n * @param resourceManager: `ResourceManager` of the `GraphModel`.\n */\n set resourceManager(resourceManager: ResourceManager) {\n this._resourceManager = resourceManager;\n }\n\n get inputs(): TensorInfo[] {\n return this._inputs.map(node => {\n return {\n name: node.name,\n shape: node.attrParams['shape'] ?\n node.attrParams['shape'].value as number[] :\n undefined,\n dtype: node.attrParams['dtype'] ?\n node.attrParams['dtype'].value as DataType :\n undefined\n };\n });\n }\n\n get outputs(): TensorInfo[] {\n return this._outputs.map(node => {\n return {\n name: node.name,\n shape: node.attrParams['shape'] ?\n node.attrParams['shape'].value as number[] :\n undefined,\n dtype: node.attrParams['dtype'] ?\n node.attrParams['dtype'].value as DataType :\n undefined\n };\n });\n }\n\n get inputNodes(): string[] {\n return this._inputs.map(node => node.signatureKey || node.name);\n }\n\n get outputNodes(): string[] {\n return this._outputs.map((node) => {\n const name = node.signatureKey || node.name;\n return node.defaultOutput ? (`${name}:${node.defaultOutput}`) : name;\n });\n }\n\n get functions(): {[key: string]: ISignatureDef} {\n return Object.keys(this._functions).reduce((map, key) => {\n map[key] = this._functions[key].signature;\n return map;\n }, {} as {[key: string]: ISignatureDef});\n }\n\n /**\n *\n * @param graph Graph the model or function graph to be executed.\n * @param parent When building function exector you need to set the parent\n * executor. Since the weights and function executor maps are set at parant\n * level, that function executor can access the function maps and weight maps\n * through the parent.\n */\n constructor(private graph: Graph, private parent?: GraphExecutor) {\n this._outputs = graph.outputs;\n this._inputs = graph.inputs;\n this._initNodes = graph.initNodes;\n this._signature = graph.signature;\n this._functions = graph.functions;\n // create sub-graph executors\n if (graph.functions != null) {\n Object.keys(graph.functions).forEach(name => {\n this._functionExecutorMap[name] =\n new GraphExecutor(graph.functions[name], this);\n });\n }\n }\n\n private getCompilationKey(inputs: Node[], outputs: Node[]): string {\n const sortedInputs = inputs.map(node => node.name).sort();\n const sortedOutputs = outputs.map(node => node.name).sort();\n return sortedInputs.join(this.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 this.resetIntermediateTensors();\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 {\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,\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 if (!this.keepTensorForDebug) {\n tensor.dispose();\n } else {\n const [nodeName, index] =\n getNodeNameAndIndex(node.name, context);\n if (this.intermediateTensors[nodeName]) {\n this.intermediateTensors[nodeName][index] = tensor;\n } else {\n this.intermediateTensors[nodeName] = [];\n this.intermediateTensors[nodeName][index] = tensor;\n }\n }\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 {\n return this._executeAsync(inputs, outputs);\n }\n\n disposeIntermediateTensors() {\n if (!this.intermediateTensors) {\n return;\n }\n Object.keys(this.intermediateTensors)\n .forEach(\n key => this.intermediateTensors[key].forEach(\n tensor => tensor.dispose()));\n this.disposeTensorsMap();\n }\n\n private disposeTensorsMap() {\n if (!this.tensorsMap) {\n return;\n }\n Object.keys(this.tensorsMap).forEach(key => {\n const tensorArray = this.tensorsMap[key];\n tensorArray.forEach(tensor => {\n if (tensor && !tensor.kept && !tensor.isDisposed &&\n !this.keepIds.has(tensor.id)) {\n tensor.dispose();\n }\n });\n });\n }\n\n getIntermediateTensors(): NamedTensorsMap {\n return this.tensorsMap;\n }\n\n private resetIntermediateTensors() {\n for (const key in this.intermediateTensors) {\n this.intermediateTensors[key].forEach(tensor => tensor.dispose());\n delete this.intermediateTensors[key];\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 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 {\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 // For model debug.\n try {\n this.keepTensorForDebug = env().getBool('KEEP_INTERMEDIATE_TENSORS');\n } catch (e) {\n console.warn(e.message);\n }\n this.resetIntermediateTensors();\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 this.tensorsMap = await this.executeWithControlFlow(\n inputs, context, outputs, isFunctionExecution);\n const results =\n outputs.map(name => getTensor(name, this.tensorsMap, context));\n\n // dispose all the intermediate tensors\n const outputIds = results.map(t => t.id);\n const inputIds = Object.keys(inputs).map(name => inputs[name].id);\n this.keepIds =\n new Set([...outputIds, ...inputIds, ...this.weightIds]);\n if (!this.keepTensorForDebug) {\n this.disposeTensorsMap();\n }\n\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(this.keepIds);\n }\n\n return results;\n }\n\n async executeFunctionAsync(\n inputs: Tensor[], tensorArrayMap: TensorArrayMap,\n tensorListMap: TensorListMap): Promise {\n const mappedInputs = inputs.reduce((map, tensor, index) => {\n map[this.inputs[index].name] = tensor;\n return map;\n }, {} as NamedTensorMap);\n\n return this._executeAsync(\n mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap);\n }\n\n /**\n * When there are control flow nodes in the graph, the graph execution use\n * ExecutionContext to keep track of the frames and loop iterators.\n * @param inputs placeholder tensors for the graph.\n * @param context the execution context object for current execution.\n * @param outputNames Optional. output node name from the Tensorflow model,\n * if no outputs are specified, the default outputs of the model would be\n * used. You can inspect intermediate nodes of the model by adding them to 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 {\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, outputNames: string[],\n intermediateTensorConsumerCount: {[key: number]: number},\n usedNodes: Set) {\n const promises: Array> = [];\n while (stack.length > 0) {\n const item = stack.pop();\n context.currentContext = item.contexts;\n let nodeName = '';\n // The tensor of the Enter op with isConstant set should be set\n // in the parent scope, so it will be available as constant for the\n // whole loop.\n if (item.node.op === 'Enter' &&\n getParamValue('isConstant', item.node, tensorMap, context)) {\n [nodeName] = getNodeNameAndIndex(item.node.name, context);\n }\n\n // only process nodes that are not in the tensorMap yet, this include\n // inputNodes and internal initNodes.\n if (tensorMap[item.node.name] == null) {\n const tensors =\n executeOp(item.node, tensorMap, context, this._resourceManager);\n if (!nodeName) {\n [nodeName] = getNodeNameAndIndex(item.node.name, context);\n }\n const currentContext = context.currentContext;\n if (util.isPromise(tensors)) {\n promises.push(tensors.then(t => {\n tensorMap[nodeName] = t;\n 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;\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) {\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, util} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\nimport {NamedTensorsMap, TensorInfo} from '../data/types';\nimport {OperationMapper} from '../operations/operation_mapper';\n\nimport {GraphExecutor} from './graph_executor';\nimport {ResourceManager} from './resource_manager';\n\nexport const TFHUB_SEARCH_PARAM = '?tfjs-format=file';\nexport const DEFAULT_MODEL_NAME = 'model.json';\ntype Url = string|io.IOHandler|io.IOHandlerSync;\ntype UrlIOHandler = T extends string ? io.IOHandler : T;\n\n/**\n * A `tf.GraphModel` is a directed, acyclic graph built from a\n * SavedModel GraphDef and allows inference execution.\n *\n * A `tf.GraphModel` can only be created by loading from a model converted from\n * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using\n * the command line converter tool and loaded via `tf.loadGraphModel`.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\nexport class GraphModel implements\n InferenceModel {\n private executor: GraphExecutor;\n private version = 'n/a';\n private handler: UrlIOHandler;\n private artifacts: io.ModelArtifacts;\n private initializer: GraphExecutor;\n private resourceManager: ResourceManager;\n private signature: tensorflow.ISignatureDef;\n private structuredOutputKeys: string[];\n private readonly io: typeof io;\n\n // Returns the version information for the tensorflow model GraphDef.\n get modelVersion(): string {\n return this.version;\n }\n\n get inputNodes(): string[] {\n return this.executor.inputNodes;\n }\n\n get outputNodes(): string[] {\n return this.executor.outputNodes;\n }\n\n get inputs(): TensorInfo[] {\n return this.executor.inputs;\n }\n\n get outputs(): TensorInfo[] {\n return this.executor.outputs;\n }\n\n get weights(): NamedTensorsMap {\n return this.executor.weightMap;\n }\n\n get metadata(): {} {\n return this.artifacts.userDefinedMetadata;\n }\n\n get modelSignature(): {} {\n return this.signature;\n }\n\n get modelStructuredOutputKeys(): {} {\n return this.structuredOutputKeys;\n }\n\n /**\n * @param modelUrl url for the model, or an `io.IOHandler`.\n * @param weightManifestUrl url for the weight file generated by\n * scripts/convert.py script.\n * @param requestOption options for Request, which allows to send credentials\n * and custom headers.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n */\n constructor(\n private modelUrl: ModelURL, private loadOptions: io.LoadOptions = {},\n tfio = io) {\n this.io = tfio;\n if (loadOptions == null) {\n this.loadOptions = {};\n }\n this.resourceManager = new ResourceManager();\n }\n\n private findIOHandler() {\n type IOHandler = UrlIOHandler;\n const path = this.modelUrl;\n if ((path as io.IOHandler).load != null) {\n // Path is an IO Handler.\n this.handler = path as IOHandler;\n } else if (this.loadOptions.requestInit != null) {\n this.handler = this.io.browserHTTPRequest(\n path as string, this.loadOptions) as IOHandler;\n } else {\n const handlers =\n this.io.getLoadHandlers(path as string, this.loadOptions);\n if (handlers.length === 0) {\n // For backward compatibility: if no load handler can be found,\n // assume it is a relative http path.\n handlers.push(\n this.io.browserHTTPRequest(path as string, this.loadOptions));\n } else if (handlers.length > 1) {\n throw new Error(\n `Found more than one (${handlers.length}) load handlers for ` +\n `URL '${[path]}'`);\n }\n this.handler = handlers[0] as IOHandler;\n }\n }\n\n /**\n * Loads the model and weight files, construct the in memory weight map and\n * compile the inference graph.\n */\n load(): UrlIOHandler extends io.IOHandlerSync? boolean:\n Promise {\n type IOHandler = UrlIOHandler;\n this.findIOHandler();\n if (this.handler.load == null) {\n throw new Error(\n 'Cannot proceed with model loading because the IOHandler provided ' +\n 'does not have the `load` method implemented.');\n }\n\n type Result =\n IOHandler extends io.IOHandlerSync ? boolean : Promise;\n\n const loadResult = this.handler.load() as ReturnType;\n if (util.isPromise(loadResult)) {\n return loadResult.then(artifacts => this.loadSync(artifacts)) as Result;\n }\n\n return this.loadSync(loadResult) as Result;\n }\n\n /**\n * Synchronously construct the in memory weight map and\n * compile the inference graph. 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 = this.artifacts.signature;\n if (this.artifacts.userDefinedMetadata != null) {\n const metadata = this.artifacts.userDefinedMetadata;\n if (metadata.signature != null) {\n signature = metadata.signature;\n }\n\n if (metadata.structuredOutputKeys != null) {\n this.structuredOutputKeys = metadata.structuredOutputKeys as string[];\n }\n }\n this.signature = signature;\n\n this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;\n const weightMap = this.io.decodeWeights(\n 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 {\n if (typeof handlerOrURL === 'string') {\n const handlers = this.io.getSaveHandlers(handlerOrURL);\n if (handlers.length === 0) {\n throw new Error(\n `Cannot find any save handlers for URL '${handlerOrURL}'`);\n } else if (handlers.length > 1) {\n throw new Error(\n `Found more than one (${handlers.length}) save handlers for ` +\n `URL '${handlerOrURL}'`);\n }\n handlerOrURL = handlers[0];\n }\n if (handlerOrURL.save == null) {\n throw new Error(\n 'GraphModel.save() cannot proceed because the IOHandler ' +\n 'provided does not have the `save` attribute defined.');\n }\n\n return handlerOrURL.save(this.artifacts);\n }\n\n /**\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.\n * Currently the batch size option is ignored for graph model.\n *\n * @returns Inference result tensors. If the model is converted and it\n * originally had structured_outputs in tensorflow, then a NamedTensorMap\n * will be returned matching the structured_outputs. If no structured_outputs\n * are present, the output will be single `tf.Tensor` if the model has single\n * output node, otherwise Tensor[].\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig):\n Tensor|Tensor[]|NamedTensorMap {\n const outputTensors = this.execute(inputs, this.outputNodes);\n if (this.structuredOutputKeys) {\n const outputTensorsArray =\n outputTensors instanceof Tensor ? [outputTensors] : outputTensors;\n const outputTensorMap: NamedTensorMap = {};\n\n outputTensorsArray.forEach(\n (outputTensor, i) => outputTensorMap[this.structuredOutputKeys[i]] =\n outputTensor);\n\n return outputTensorMap;\n }\n return outputTensors;\n }\n\n 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 {\n inputs = this.normalizeInputs(inputs);\n outputs = this.normalizeOutputs(outputs);\n const result = await this.executor.executeAsync(inputs, outputs);\n return result.length > 1 ? result : result[0];\n }\n\n /**\n * Get intermediate tensors for model debugging mode (flag\n * KEEP_INTERMEDIATE_TENSORS is true).\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n getIntermediateTensors(): NamedTensorsMap {\n return this.executor.getIntermediateTensors();\n }\n\n /**\n * Dispose intermediate tensors for model debugging mode (flag\n * KEEP_INTERMEDIATE_TENSORS is true).\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n disposeIntermediateTensors() {\n this.executor.disposeIntermediateTensors();\n }\n\n private convertTensorMapToTensorsMap(map: NamedTensorMap): NamedTensorsMap {\n return Object.keys(map).reduce((newMap: NamedTensorsMap, key) => {\n newMap[key] = [map[key]];\n return newMap;\n }, {});\n }\n\n /**\n * Releases the memory used by the weight tensors and resourceManager.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n dispose() {\n this.executor.dispose();\n\n if (this.initializer) {\n this.initializer.dispose();\n }\n\n this.resourceManager.dispose();\n }\n}\n\n/**\n * Load a graph model given a URL to the model definition.\n *\n * Example of loading MobileNetV2 from a URL and making a prediction with a\n * zeros input:\n *\n * ```js\n * const modelUrl =\n * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n * const model = await tf.loadGraphModel(modelUrl);\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n *\n * Example of loading MobileNetV2 from a TF Hub URL and making a prediction\n * with a zeros input:\n *\n * ```js\n * const modelUrl =\n * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';\n * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n * @param modelUrl The url or an `io.IOHandler` that loads the model.\n * @param options Options for the HTTP request, which allows to send\n * credentials\n * and custom headers.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport async function loadGraphModel(\n modelUrl: string|io.IOHandler, options: io.LoadOptions = {},\n tfio = io): Promise {\n if (modelUrl == null) {\n throw new Error(\n 'modelUrl in loadGraphModel() cannot be null. Please provide a url ' +\n 'or an IOHandler that loads the model');\n }\n if (options == null) {\n options = {};\n }\n\n if (options.fromTFHub && typeof modelUrl === 'string') {\n modelUrl = getTFHubUrl(modelUrl);\n }\n const model = new GraphModel(modelUrl, options, tfio);\n await model.load();\n return model;\n}\n\n/**\n * Load a graph model given a synchronous IO handler with a 'load' method.\n *\n * @param modelSource The `io.IOHandlerSync` that loads the model, or the\n * `io.ModelArtifacts` that encode the model, or a tuple of\n * `[io.ModelJSON, ArrayBuffer]` of which the first element encodes the\n * model and the second contains the weights.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport function loadGraphModelSync(modelSource: io.IOHandlerSync\n | io.ModelArtifacts | [io.ModelJSON, /* Weights */ ArrayBuffer]):\n GraphModel {\n\n if (modelSource == null) {\n throw new Error(\n 'modelUrl in loadGraphModelSync() cannot be null. Please provide ' +\n 'model artifacts or an IOHandler that loads the model');\n }\n\n let ioHandler: io.IOHandlerSync;\n if (modelSource instanceof Array) {\n const [modelJSON, weights] = modelSource;\n if (!modelJSON) {\n throw new Error('modelJSON must be the first element of the array');\n }\n if (!weights || !(weights instanceof ArrayBuffer)) {\n throw new Error('An ArrayBuffer of weights must be the second element of'\n + ' the array');\n }\n if (!('modelTopology' in modelJSON)) {\n throw new Error('Model JSON is missing \\'modelTopology\\'');\n }\n if (!('weightsManifest' in modelJSON)) {\n throw new Error('Model JSON is missing \\'weightsManifest\\'');\n }\n\n const weightSpecs = io.getWeightSpecs(modelJSON.weightsManifest);\n const modelArtifacts = io.getModelArtifactsForJSONSync(modelJSON,\n weightSpecs,\n weights);\n ioHandler = io.fromMemorySync(modelArtifacts);\n } else if ('load' in modelSource) {\n // Then modelSource is already an IOHandlerSync.\n ioHandler = modelSource;\n } else if ('modelTopology' in modelSource && 'weightSpecs' in modelSource\n && 'weightData' in modelSource) {\n // modelSource is of type ModelArtifacts.\n ioHandler = io.fromMemorySync(modelSource);\n } else {\n throw new Error('Unknown model format');\n }\n\n const model = new GraphModel(ioHandler);\n model.load();\n return model;\n}\n\nfunction getTFHubUrl(modelUrl: string): string {\n if (!modelUrl.endsWith('/')) {\n modelUrl = (modelUrl) + '/';\n }\n return `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;\n}\n","/**\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{tensor2d,tensor1d,util,tidy}from\"@tensorflow/tfjs-core\";import{loadGraphModel}from\"@tensorflow/tfjs-converter\";function __awaiter(e,n,t,r){return new(t||(t=Promise))(function(o,i){function a(e){try{u(r.next(e))}catch(e){i(e)}}function s(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t(function(e){e(n)})).then(a,s)}u((r=r.apply(e,n||[])).next())})}function __generator(e,n){var t,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},\"function\"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(t)throw new TypeError(\"Generator is already executing.\");for(;a;)try{if(t=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?separator+n.replace(/ /g,separator):n}var RESERVED_SYMBOLS_COUNT=6,Tokenizer=function(){function e(e,n){void 0===n&&(n=RESERVED_SYMBOLS_COUNT),this.vocabulary=e,this.reservedSymbolsCount=n,this.trie=new Trie;for(var t=this.reservedSymbolsCount;t=r[c])&&(r[c]=_,t[c]=d[s].index)}}for(var v=[],p=t.length-1;p>0;)v.push(t[p]),p-=this.vocabulary[t[p]][0].length;var E=[],T=!1;for(i=0;i=e.length?e[t]=TOKEN_PADDING:SKIP_VALUES.includes(e[t])||(e[t]+=OFFSET);return e.slice(0,n)},e}(),BASE_PATH$1=\"https://storage.googleapis.com/tfjs-models/savedmodel/universal_sentence_encoder\";function load(e){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(t){switch(t.label){case 0:return[4,(n=new UniversalSentenceEncoder).load(e)];case 1:return t.sent(),[2,n]}})})}var UniversalSentenceEncoder=function(){function e(){}return e.prototype.loadModel=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(n){return[2,e?loadGraphModel(e):loadGraphModel(\"https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder-lite/1/default/1\",{fromTFHub:!0})]})})},e.prototype.load=function(e){return void 0===e&&(e={}),__awaiter(this,void 0,void 0,function(){var n,t,r;return __generator(this,function(o){switch(o.label){case 0:return[4,Promise.all([this.loadModel(e.modelUrl),loadVocabulary(e.vocabUrl||BASE_PATH$1+\"/vocab.json\")])];case 1:return n=o.sent(),t=n[0],r=n[1],this.model=t,this.tokenizer=new Tokenizer(r),[2]}})})},e.prototype.embed=function(e){return __awaiter(this,void 0,void 0,function(){var n,t,r,o,i,a,s,u,l=this;return __generator(this,function(c){switch(c.label){case 0:for(\"string\"==typeof e&&(e=[e]),n=e.map(function(e){return l.tokenizer.encode(e)}),t=n.map(function(e,n){return e.map(function(e,t){return[n,t]})}),r=[],o=0;o;\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 {\n private data = new WeakMap();\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;\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 {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n readToGPU(dataId: object, options?: DataToGPUOptions): GPUData {\n return notYetImplemented('readToGPU');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object, force?: boolean): boolean {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n return notYetImplemented('move');\n }\n\n createTensorFromGPUData(\n values: WebGLData|WebGPUData, shape: number[], dtype: DataType): Tensor {\n return notYetImplemented('createTensorFromGPUData');\n }\n\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, TensorLike, TypedArray, WebGLData, WebGPUData} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n swap(array, counter, index);\n }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n * as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n // tslint:disable-next-line:no-any\n array: any[]|Uint32Array|Int32Array|Float32Array,\n // tslint:disable-next-line:no-any\n array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n if (array.length !== array2.length) {\n throw new Error(\n `Array sizes must match to be shuffled together ` +\n `First array length was ${array.length}` +\n `Second array length was ${array2.length}`);\n }\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element of each array with it\n swap(array, counter, index);\n swap(array2, counter, index);\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap(\n object: {[index: number]: T}, left: number, right: number) {\n const temp = object[left];\n object[left] = object[right];\n object[right] = temp;\n}\n\nexport function sum(arr: number[]): number {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n const r = Math.random();\n return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n const diff = Number(a[i]) - Number(b[i]);\n result += diff * diff;\n }\n return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n * error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n if (!expr) {\n throw new Error(typeof msg === 'string' ? msg : msg());\n }\n}\n\nexport function assertShapesMatch(\n shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n assert(\n arraysEqual(shapeA, shapeB),\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n assert(\n a != null,\n () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n if (shape.length === 0) {\n // Scalar.\n return 1;\n }\n let size = shape[0];\n for (let i = 1; i < shape.length; i++) {\n size *= shape[i];\n }\n return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n return shape.length === 0;\n}\n\nexport function arraysEqualWithNull(n1: number[], n2: number[]) {\n if (n1 === n2) {\n return true;\n }\n\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n if (n1 === n2) {\n return true;\n }\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function isInt(a: number): boolean {\n return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n // tslint:disable-next-line:no-any\n if ((Math as any).tanh != null) {\n // tslint:disable-next-line:no-any\n return (Math as any).tanh(x);\n }\n if (x === Infinity) {\n return 1;\n } else if (x === -Infinity) {\n return -1;\n } else {\n const e2x = Math.exp(2 * x);\n return (e2x - 1) / (e2x + 1);\n }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n const width = Math.ceil(Math.sqrt(size));\n return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indices to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indices to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number,\n scheduleFn?: (functionRef: Function, delay: number) =>\n void): Promise {\n return new Promise((resolve, reject) => {\n let tryCount = 0;\n\n const tryFn = () => {\n if (checkFn()) {\n resolve();\n return;\n }\n\n tryCount++;\n\n const nextBackoff = delayFn(tryCount);\n\n if (maxCounter != null && tryCount >= maxCounter) {\n reject();\n return;\n }\n\n if (scheduleFn != null) {\n scheduleFn(tryFn, nextBackoff);\n } else {\n // google3 does not allow assigning another variable to setTimeout.\n // Don't refactor this so scheduleFn has a default value of setTimeout.\n setTimeout(tryFn, nextBackoff);\n }\n };\n\n tryFn();\n });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n shape: number[], size: number): number[] {\n let shapeProd = 1;\n let implicitIdx = -1;\n\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] >= 0) {\n shapeProd *= shape[i];\n } else if (shape[i] === -1) {\n if (implicitIdx !== -1) {\n throw Error(\n `Shapes can only have 1 implicit size. ` +\n `Found -1 at dim ${implicitIdx} and dim ${i}`);\n }\n implicitIdx = i;\n } else if (shape[i] < 0) {\n throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n }\n }\n\n if (implicitIdx === -1) {\n if (size > 0 && size !== shapeProd) {\n throw Error(`Size(${size}) must match the product of shape ${shape}`);\n }\n return shape;\n }\n\n if (shapeProd === 0) {\n throw Error(\n `Cannot infer the missing size in [${shape}] when ` +\n `there are 0 elements`);\n }\n if (size % shapeProd !== 0) {\n throw Error(\n `The implicit shape can't be a fractional number. ` +\n `Got ${size} / ${shapeProd}`);\n }\n\n const newShape = shape.slice();\n newShape[implicitIdx] = size / shapeProd;\n return newShape;\n}\n\nexport function parseAxisParam(\n axis: number|number[], shape: number[]): number[] {\n const rank = shape.length;\n\n // Normalize input\n axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n // Check for valid range\n assert(\n axis.every(ax => ax >= -rank && ax < rank),\n () =>\n `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n `got axis ${axis}`);\n\n // Check for only integers\n assert(\n axis.every(ax => isInt(ax)),\n () => `All values in axis param must be integers but ` +\n `got axis ${axis}`);\n\n // Handle negative axis.\n return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n {newShape: number[], keptDims: number[]} {\n const newShape: number[] = [];\n const keptDims: number[] = [];\n const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n const axes = (axis == null || isEmptyArray) ?\n null :\n parseAxisParam(axis, shape).sort();\n let j = 0;\n for (let i = 0; i < shape.length; ++i) {\n if (axes != null) {\n if (axes[j] === i && shape[i] !== 1) {\n throw new Error(\n `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n }\n if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n if (axes[j] <= i) {\n j++;\n }\n }\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n }\n return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n return getArrayFromDType(dtype, size);\n}\n\nexport function getArrayFromDType(\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(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors(\n vals: DataTypeMap[D]|number[], dtype: D): void {\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n }\n }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n if (newType === 'complex64') {\n return false;\n }\n if (newType === 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'bool' && oldType === 'bool') {\n return false;\n }\n return true;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS\n * is not possible since it depends on the encoding of the html page that\n * serves the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike|WebGLData|WebGPUData): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (\n values instanceof Int32Array || values instanceof Uint8Array ||\n values instanceof Uint8ClampedArray) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\nfunction createNestedArray(\n offset: number, shape: number[], a: TypedArray, isComplex = false) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0] * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n shape: number[], a: TypedArray, isComplex = false) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}${\n isComplex ? ' for a complex tensor' : ''}.`);\n }\n\n return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function convertBackendValuesAndArrayBuffer(\n data: BackendValues|ArrayBuffer, dtype: DataType) {\n // If is type Uint8Array[], return it directly.\n if (Array.isArray(data)) {\n return data;\n }\n if (dtype === 'float32') {\n return data instanceof Float32Array ? data : new Float32Array(data);\n } else if (dtype === 'int32') {\n return data instanceof Int32Array ? data : new Int32Array(data);\n } else if (dtype === 'bool' || dtype === 'string') {\n return Uint8Array.from(new Int32Array(data));\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\nexport function makeOnesTypedArray(\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(\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(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a\n * tensor/multidimentional array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise {\n // We chose to not use 'obj instanceOf Promise' for two reasons:\n // 1. It only reliably works for es6 Promise, not other Promise\n // implementations.\n // 2. It doesn't work with framework that uses zone.js. zone.js monkey\n // patch the async calls, so it is possible the obj (patched) is\n // comparing to a pre-patched Promise.\n return object && object.then && typeof object.then === 'function';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean|string;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // Jasmine spies on this in 'environment_test.ts'\n getQueryParams = getQueryParams;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platformName}.`);\n }\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because\n // the environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n }\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (isPromise(flagValue)) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue;\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n getString(flagName: string): string {\n return this.get(flagName) as string;\n }\n\n getFlags(): Flags {\n return this.flags;\n }\n // For backwards compatibility.\n get features(): Flags {\n return this.flags;\n }\n\n set(flagName: string, value: FlagValue): void {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot set flag ${flagName} as it has not been registered.`);\n }\n this.flags[flagName] = value;\n if (this.flagRegistry[flagName].setHook != null) {\n this.flagRegistry[flagName].setHook(value);\n }\n }\n\n private evaluateFlag(flagName: string): FlagValue|Promise {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = this.getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n const lowerCaseValue = value.toLowerCase();\n if (lowerCaseValue === 'true' || lowerCaseValue === 'false') {\n return lowerCaseValue === 'true';\n } else if (`${+ lowerCaseValue}` === lowerCaseValue) {\n return +lowerCaseValue;\n } else {\n return value;\n }\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map} {\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 {\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(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {TensorInfo} from './tensor_info';\nimport {DataType, DrawOptions, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick;\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;\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;\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;\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;\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;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick;\nexport interface BincountAttrs {\n size: number;\n}\n\nexport const BitwiseAnd = 'BitwiseAnd';\nexport type BitwiseAndInputs = BinaryInputs;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick;\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;\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;\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;\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;\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;\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;\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;\nexport interface Conv3DBackpropInputV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumprod = 'Cumprod';\nexport type CumprodInputs = Pick;\nexport interface CumprodAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick;\nexport interface DenseBincountAttrs {\n size: number;\n binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick;\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;\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;\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;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick;\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;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick;\n\nexport const Draw = 'Draw';\nexport type DrawInputs = Pick;\nexport interface DrawAttrs {\n canvas: HTMLCanvasElement;\n options?: DrawOptions;\n}\n\nexport const RealDiv = 'RealDiv';\nexport type RealDivInputs = BinaryInputs;\n\nexport const Einsum = 'Einsum';\nexport type EinsumInputs = TensorInfo[];\nexport interface EinsumAttrs {\n equation: string;\n}\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick;\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;\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;\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;\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;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick;\nexport interface GatherV2Attrs {\n axis: number;\n batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick;\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;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick;\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;\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;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogicalXor = 'LogicalXor';\nexport type LogicalXorInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LowerBound = 'LowerBound';\nexport type LowerBoundInputs =\n Pick;\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick;\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;\nexport interface LRNGradAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const MatrixBandPart = 'MatrixBandPart';\nexport type MatrixBandPartInputs =\n Pick;\nexport interface MatrixBandPartAttrs {}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick;\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;\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;\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;\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;\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;\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;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick;\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;\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;\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;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick;\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;\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;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n dtype: DataType;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const RaggedGather = 'RaggedGather';\nexport type RaggedGatherInputs = {\n paramsNestedSplits: TensorInfo[]\n}&Pick;\nexport interface RaggedGatherAttrs {\n outputRaggedRank: number;\n}\n\nexport const RaggedRange = 'RaggedRange';\nexport type RaggedRangeInputs =\n Pick;\n\nexport const RaggedTensorToTensor = 'RaggedTensorToTensor';\nexport type RaggedTensorToTensorInputs =\n Pick&\n {rowPartitionTensors: TensorInfo[]};\nexport interface RaggedTensorToTensorAttrs {\n rowPartitionTypes: string[];\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick;\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;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const TensorScatterUpdate = 'TensorScatterUpdate';\nexport type TensorScatterUpdateInputs =\n Pick;\nexport interface TensorScatterUpdateAttrs {}\n\nexport const SearchSorted = 'SearchSorted';\nexport type SearchSortedInputs =\n Pick;\nexport interface SearchSortedAttrs {\n side: 'left'|'right';\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick;\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;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n Pick;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n Pick;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n Pick;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n Pick;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick;\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;\n\nexport const StaticRegexReplace = 'StaticRegexReplace';\nexport type StaticRegexReplaceInputs = UnaryInputs;\nexport interface StaticRegexReplaceAttrs {\n pattern: string;\n rewrite: string;\n replaceGlobal: boolean;\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick;\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;\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;\nexport interface StringSplitAttrs {\n skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick;\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;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick;\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;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const UpperBound = 'UpperBound';\nexport type UpperBoundInputs =\n Pick;\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;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(...msg);\n }\n}\n\nexport function log(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.log(...msg);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {TensorInfo} from './tensor_info';\nimport {RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map<`${string}_${string}`,\n KernelConfig>());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map());\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;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n inputs: NamedTensorInfoMap,\n backend: {},\n attrs?: NamedAttrMap,\n}) => TensorInfo | TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n (dy: Tensor | Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n kernelName: string;\n backendName: string;\n kernelFunc: KernelFunc;\n setupFunc?: KernelSetupFunc;\n disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n kernelName: string;\n inputsToSave?: string[];\n // When saveAllInputs is true, all inputs will be saved. Only use this flag\n // if inputs is an array of Tensors.\n saveAllInputs?: boolean;\n outputsToSave?: boolean[];\n gradFunc: GradFunc;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo|undefined;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n log.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n log.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string,\n backendName: string): `${string}_${string}` {\n return `${backendName}_${kernelName}`;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport function isTypedArrayBrowser(a: unknown): a is Uint8Array\n | Float32Array | Int32Array | Uint8ClampedArray {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Workaround for allowing cjs module to be included in bundle created by\n// rollup.\nimport * as LongExports from 'long';\n// tslint:disable-next-line\nconst Long: LongExports.LongConstructor =\n // tslint:disable-next-line\n (LongExports as any).default || LongExports;\n\nexport function hexToLong(hex: string): Long {\n return Long.fromString(hex, true, 16);\n}\n\n// Some primes between 2^63 and 2^64 for various uses.\n// Hex 0xc3a5c85c97cb3127\nconst k0: Long = hexToLong('c3a5c85c97cb3127');\n// Hex 0xb492b66fbe98f273\nconst k1: Long = hexToLong('b492b66fbe98f273');\n// Hex 0x9ae16a3b2f90404f\nconst k2: Long = hexToLong('9ae16a3b2f90404f');\n\nfunction shiftMix(val: Long): Long {\n return val.xor(val.shru(47));\n}\n\nfunction fetch(s: Uint8Array, offset: number, numBytes: number): Long {\n const bytes = s.slice(offset, offset + numBytes);\n return Long.fromBytes(Array.from(bytes), true, true);\n}\n\nfunction fetch64(s: Uint8Array, offset: number): Long {\n return fetch(s, offset, 8);\n}\n\nfunction fetch32(s: Uint8Array, offset: number): Long {\n return fetch(s, offset, 4);\n}\n\nfunction rotate64(val: Long, shift: number): Long {\n // Avoid shifting by 64: doing so yields an undefined result.\n return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));\n}\n\nfunction hashLen16(u: Long, v: Long, mul = hexToLong('9ddfea08eb382d69')) {\n // Murmur-inspired hashing.\n let a = u.xor(v).mul(mul);\n a = a.xor(a.shru(47));\n let b = v.xor(a).mul(mul);\n b = b.xor(b.shru(47));\n b = b.mul(mul);\n return b;\n}\n\n// Return a 16-byte hash for 48 bytes. Quick and dirty.\n// Callers do best to use \"random-looking\" values for a and b.\nfunction weakHashLen32WithSeeds(\n w: Long, x: Long, y: Long, z: Long, a: Long, b: Long) {\n a = a.add(w);\n b = rotate64(b.add(a).add(z), 21);\n const c = a;\n a = a.add(x);\n a = a.add(y);\n b = b.add(rotate64(a, 44));\n return [a.add(z), b.add(c)];\n}\n\nfunction weakHashLen32WithSeedsStr(\n s: Uint8Array, offset: number, a: Long, b: Long) {\n return weakHashLen32WithSeeds(\n fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16),\n fetch64(s, offset + 24), a, b);\n}\n\nfunction hashLen0to16(s: Uint8Array, len = s.length): Long {\n if (len >= 8) {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).add(k2);\n const b = fetch64(s, len - 8);\n const c = rotate64(b, 37).mul(mul).add(a);\n const d = rotate64(a, 25).add(b).mul(mul);\n return hashLen16(c, d, mul);\n }\n if (len >= 4) {\n const mul = k2.add(len * 2);\n const a = fetch32(s, 0);\n return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);\n }\n if (len > 0) {\n const a = s[0];\n const b = s[len >> 1];\n const c = s[len - 1];\n const y = a + (b << 8);\n const z = len + (c << 2);\n return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);\n }\n return k2;\n}\n\nfunction hashLen17to32(s: Uint8Array, len = s.length): Long {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).mul(k1);\n const b = fetch64(s, 8);\n const c = fetch64(s, len - 8).mul(mul);\n const d = fetch64(s, len - 16).mul(k2);\n return hashLen16(\n rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d),\n a.add(rotate64(b.add(k2), 18)).add(c), mul);\n}\n\nfunction hashLen33to64(s: Uint8Array, len = s.length): Long {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).mul(k2);\n const b = fetch64(s, 8);\n const c = fetch64(s, len - 8).mul(mul);\n const d = fetch64(s, len - 16).mul(k2);\n const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);\n const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);\n const e = fetch64(s, 16).mul(mul);\n const f = fetch64(s, 24);\n const g = y.add(fetch64(s, len - 32)).mul(mul);\n const h = z.add(fetch64(s, len - 24)).mul(mul);\n return hashLen16(\n rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h),\n e.add(rotate64(f.add(a), 18)).add(g), mul);\n}\n\nexport function fingerPrint64(s: Uint8Array, len = s.length): Long {\n const seed: Long = Long.fromNumber(81, true);\n if (len <= 32) {\n if (len <= 16) {\n return hashLen0to16(s, len);\n } else {\n return hashLen17to32(s, len);\n }\n } else if (len <= 64) {\n return hashLen33to64(s, len);\n }\n\n // For strings over 64 bytes we loop. Internal state consists of\n // 56 bytes: v, w, x, y, and z.\n let x = seed;\n let y = seed.mul(k1).add(113);\n\n let z = shiftMix(y.mul(k2).add(113)).mul(k2);\n let v = [Long.UZERO, Long.UZERO];\n let w = [Long.UZERO, Long.UZERO];\n x = x.mul(k2).add(fetch64(s, 0));\n\n let offset = 0;\n // Set end so that after the loop we have 1 to 64 bytes left to process.\n const end = ((len - 1) >> 6) * 64;\n const last64 = end + ((len - 1) & 63) - 63;\n\n do {\n x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);\n y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);\n x = x.xor(w[1]);\n y = y.add(v[0]).add(fetch64(s, offset + 40));\n z = rotate64(z.add(w[0]), 33).mul(k1);\n v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));\n w = weakHashLen32WithSeedsStr(\n s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n [z, x] = [x, z];\n offset += 64;\n } while (offset !== end);\n const mul = k1.add(z.and(0xff).shl(1));\n // Point to the last 64 bytes of input.\n offset = last64;\n\n w[0] = w[0].add((len - 1) & 63);\n v[0] = v[0].add(w[0]);\n w[0] = w[0].add(v[0]);\n\n x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);\n y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);\n x = x.xor(w[1].mul(9));\n y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));\n z = rotate64(z.add(w[0]), 33).mul(mul);\n v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));\n w = weakHashLen32WithSeedsStr(\n s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n [z, x] = [x, z];\n\n return hashLen16(\n hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z),\n hashLen16(v[1], w[1], mul).add(x), mul);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {isTypedArrayBrowser} from './platforms/is_typed_array_browser';\nimport {BackendValues, DataType, RecursiveArray, TensorLike, TypedArray} from './types';\nimport * as base from './util_base';\nexport * from './util_base';\nexport * from './hash_util';\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n value: DataType, dtype: DataType): BackendValues {\n if (dtype === 'string') {\n return encodeString(value);\n }\n\n return toTypedArray([value], dtype);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n return (a instanceof Float32Array && dtype === 'float32') ||\n (a instanceof Int32Array && dtype === 'int32') ||\n (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n if (dtype === 'string') {\n throw new Error('Cannot convert a string[] to a TypedArray');\n }\n if (Array.isArray(a)) {\n a = flatten(a);\n }\n\n if (env().getBool('DEBUG')) {\n base.checkConversionForErrors(a as number[], dtype);\n }\n if (noConversionNeeded(a, dtype)) {\n return a as TypedArray;\n }\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(a as number[]);\n } else if (dtype === 'int32') {\n return new Int32Array(a as number[]);\n } else if (dtype === 'bool') {\n const bool = new Uint8Array((a as number[]).length);\n for (let i = 0; i < bool.length; ++i) {\n if (Math.round((a as number[])[i]) !== 0) {\n bool[i] = 1;\n }\n }\n return bool;\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n return env().platform.now();\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n path: string, requestInits?: RequestInit): Promise {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array|\n Uint8ClampedArray {\n // TODO(mattsoulanille): Remove this fallback in 5.0.0\n if (env().platform.isTypedArray != null) {\n return env().platform.isTypedArray(a);\n } else {\n return isTypedArrayBrowser(a);\n }\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten().\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|TypedArray>(\n arr: T|RecursiveArray, result: T[] = [], skipTypedArray = false): T[] {\n if (result == null) {\n result = [];\n }\n if (typeof arr === 'boolean' || typeof arr === 'number' ||\n typeof arr === 'string' || base.isPromise(arr) || arr == null ||\n isTypedArray(arr) && skipTypedArray) {\n result.push(arr as T);\n } else if (Array.isArray(arr) || isTypedArray(arr)) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n let maxIndex = -1;\n for (const key of Object.keys(arr)) {\n // 0 or positive integer.\n if (/^([1-9]+[0-9]*|0)$/.test(key)) {\n maxIndex = Math.max(maxIndex, Number(key));\n }\n }\n for (let i = 0; i <= maxIndex; i++) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n flatten((arr as RecursiveArray)[i], result, skipTypedArray);\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer, BackendTimingInfo} from './backends/backend';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n kernelName: string,\n outputs: Tensor[],\n inputs: NamedTensorMap,\n timeMs: Promise,\n extraInfo: Promise\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;\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(\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from(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 =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from(vals);\n\n return [\n '[' +\n displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ']'\n ];\n }\n\n // The array is rank 2 or more.\n const subshape = shape.slice(1);\n const substrides = strides.slice(1);\n const stride = strides[0] * storagePerElement;\n const lines: string[] = [];\n if (size > FORMAT_LIMIT_NUM_VALS) {\n for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n false /* isLast */));\n }\n lines.push('...');\n for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n } else {\n for (let i = 0; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n }\n const sep = rank === 2 ? ',' : '';\n lines[0] = '[' + (size > 0 ? lines[0] + sep : '');\n for (let i = 1; i < lines.length - 1; i++) {\n lines[i] = ' ' + lines[i] + sep;\n }\n let newLineSep = ',\\n';\n for (let i = 2; i < rank; i++) {\n newLineSep += '\\n';\n }\n lines[lines.length - 1] =\n ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n TypedArray): Array<[number, number]> {\n const complexTuples: Array<[number, number]> = [];\n for (let i = 0; i < vals.length; i += 2) {\n complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n }\n return complexTuples;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265\n/// \n\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\nimport {DataId, TensorInfo} from './tensor_info';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData {\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 {\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 {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor;\n }\n}\n\nexport interface DataToGPUWebGLOption {\n customTexShape?: [number, number];\n}\n\nexport type DataToGPUOptions = DataToGPUWebGLOption;\n\nexport interface GPUData {\n tensorRef: Tensor;\n texture?: WebGLTexture;\n buffer?: GPUBuffer;\n texShape?: [number, number];\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast(x: T, dtype: DataType): T;\n buffer(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer;\n print(x: T, verbose: boolean): void;\n clone(x: T): T;\n // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n deprecationWarningFn = fn;\n}\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * For performance reasons, functions that create tensors do not necessarily\n * perform a copy of the data passed to them (e.g. if the data is passed as a\n * `Float32Array`), and changes to the data will change the tensor. This is not\n * a feature and is not supported. To avoid this behavior, use the tensor before\n * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor implements TensorInfo {\n /** Unique id of this tensor. */\n readonly id: number;\n /**\n * Id of the bucket holding the data for this tensor. Multiple arrays can\n * point to the same bucket (e.g. when calling array.reshape()).\n */\n dataId: DataId;\n /** The shape of the tensor. */\n readonly shape: ShapeMap[R];\n /** Number of elements in the tensor. */\n readonly size: number;\n /** The data type for the array. */\n readonly dtype: DataType;\n /** The rank type for the array (see `Rank` enum). */\n readonly rankType: R;\n\n /** Whether this tensor has been globally kept. */\n kept = false;\n /** The id of the scope this tensor is being tracked in. */\n scopeId: number;\n /** The keras mask that some keras layers attach to the tensor */\n kerasMask?: Tensor;\n\n /**\n * Number of elements to skip in each dimension when indexing. See\n * https://docs.scipy.org/doc/numpy/reference/generated/\\\n * numpy.ndarray.strides.html\n */\n readonly strides: number[];\n\n constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n this.shape = shape.slice() as ShapeMap[R];\n this.dtype = dtype || 'float32';\n this.size = util.sizeFromShape(shape);\n this.strides = computeStrides(shape);\n this.dataId = dataId;\n this.id = id;\n this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n }\n\n get rank(): number {\n return this.shape.length;\n }\n\n /**\n * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async buffer(): Promise> {\n const vals = await this.data();\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(): TensorBuffer {\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 {\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(): Promise {\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;\n }\n\n /**\n * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`\n * and `data()`, this method prevents data from being downloaded to CPU.\n *\n * For WebGL backend, the data will be stored on a densely packed texture.\n * This means that the texture will use the RGBA channels to store value.\n *\n * For WebGPU backend, the data will be stored on a buffer. There is no\n * parameter, so can not use a user-defined size to create the buffer.\n *\n * @param options:\n * For WebGL,\n * - customTexShape: Optional. If set, will use the user defined\n * texture shape to create the texture.\n *\n * @returns For WebGL backend, a GPUData contains the new texture and\n * its information.\n * {\n * tensorRef: The tensor that is associated with this texture,\n * texture: WebGLTexture,\n * texShape: [number, number] // [height, width]\n * }\n *\n * For WebGPU backend, a GPUData contains the new buffer.\n * {\n * tensorRef: The tensor that is associated with this buffer,\n * buffer: GPUBuffer,\n * }\n *\n * Remember to dispose the GPUData after it is used by\n * `res.tensorRef.dispose()`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataToGPU(options?: DataToGPUOptions): GPUData {\n this.throwIfDisposed();\n return trackerFn().readToGPU(this.dataId, options);\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync(): 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 {\n this.throwIfDisposed();\n const data = await trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n return data as Uint8Array[];\n } else {\n return new Uint8Array((data as TypedArray).buffer);\n }\n }\n\n /**\n * Disposes `tf.Tensor` from memory.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n if (this.kerasMask) {\n this.kerasMask.dispose();\n }\n trackerFn().disposeTensor(this);\n this.isDisposedInternal = true;\n }\n\n protected isDisposedInternal = false;\n get isDisposed(): boolean {\n return this.isDisposedInternal;\n }\n\n throwIfDisposed() {\n if (this.isDisposed) {\n throw new Error(`Tensor is disposed.`);\n }\n }\n\n /**\n * Prints the `tf.Tensor`. See `tf.print` for details.\n *\n * @param verbose Whether to print verbose information about the tensor,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n print(verbose = false): void {\n return opHandler.print(this, verbose);\n }\n\n /**\n * Returns a copy of the tensor. See `tf.clone` for details.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n clone(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(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable;\n }\n}\n\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport function getGlobalTensorClass() {\n // Use getGlobal so that we can augment the Tensor class across package\n // boundaries 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 extends Tensor {\n dtype: NumericDataType;\n dataSync(): DataTypeMap[D];\n data(): Promise;\n dataToGPU(options?: DataToGPUOptions): GPUData;\n}\n\nexport interface StringTensor extends Tensor {\n dtype: 'string';\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor;\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 extends Tensor {\n name: string;\n\n constructor(\n initialValue: Tensor, 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): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n override dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n R0: number[];\n R1: [number];\n R2: [number, number];\n R3: [number, number, number];\n R4: [number, number, number, number];\n R5: [number, number, number, number, number];\n R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n R0: number;\n R1: number[];\n R2: number[][];\n R3: number[][][];\n R4: number[][][][];\n R5: number[][][][][];\n R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n float32: Float32Array;\n int32: Int32Array;\n bool: Uint8Array;\n complex64: Float32Array;\n string: string[];\n}\n\nexport interface SingleValueMap {\n bool: boolean;\n int32: number;\n float32: number;\n complex64: number;\n string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\n\nexport type DataTypeFor =\n T extends number|boolean ? NumericDataType : T extends string ? 'string' :\n never;\n\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n R0 = 'R0',\n R1 = 'R1',\n R2 = 'R2',\n R3 = 'R3',\n R4 = 'R4',\n R5 = 'R5',\n R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray {\n [index: number]: T|RecursiveArray;\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|\n RecursiveArray|RecursiveArray|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\n/**\n * Type for representing all permutations and combinations of 'RGBA' channels.\n */\nexport type WebGLChannels = 'A'|'B'|'G'|'R'|'AB'|'AG'|'AR'|'BA'|'BG'|'BR'|'GA'|\n 'GB'|'GR'|'RA'|'RB'|'RG'|'ABG'|'ABR'|'AGB'|'AGR'|'ARB'|'ARG'|'BAG'|'BAR'|\n 'BGA'|'BGR'|'BRA'|'BRG'|'GAB'|'GAR'|'GBA'|'GBR'|'GRA'|'GRB'|'RAB'|'RAG'|\n 'RBA'|'RBG'|'RGA'|'RGB'|'ABGR'|'ABRG'|'AGBR'|'AGRB'|'ARBG'|'ARGB'|'BAGR'|\n 'BARG'|'BGAR'|'BGRA'|'BRAG'|'BRGA'|'GABR'|'GARB'|'GBAR'|'GBRA'|'GRAB'|\n 'GRBA'|'RABG'|'RAGB'|'RBAG'|'RBGA'|'RGAB'|'RGBA';\n\n/** Type for representing a texture data to create a tensor. */\nexport interface WebGLData {\n texture: WebGLTexture;\n height: number;\n width: number;\n channels: WebGLChannels;\n}\n\n/**\n * Type for representing a buffer data to create a tensor. Buffer usage should\n * at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC. When\n * zeroCopy is false or undefined (default), this GPUBuffer will be copied to\n * the tensor's resource buffer. When zeroCopy is true, tensor will use this\n * GPUBuffer as tensor's resource buffer, user should not destroy this GPUBuffer\n * until all access is done. If not specified at creating a tensor, tensor type\n * is float32.\n */\nexport interface WebGPUData {\n buffer: GPUBuffer;\n zeroCopy?: boolean;\n}\n\nexport function isWebGLData(values: unknown): values is WebGLData {\n return values != null && typeof values === 'object' && 'texture' in values &&\n values.texture instanceof WebGLTexture;\n}\nexport function isWebGPUData(values: unknown): values is WebGPUData {\n return typeof GPUBuffer !== 'undefined' && values != null &&\n typeof values === 'object' && 'buffer' in values &&\n values.buffer instanceof GPUBuffer;\n}\n\nexport interface ImageOptions {\n /**\n * Optional. A number in range [0-1]. If the image is a 2D tensor or a 3D\n * tensor with 1 or 3 channels, the alpha channels would set as its value;\n * otherwise, it would not make effects.\n */\n alpha?: number;\n}\n\nexport interface ContextOptions {\n /**\n * Optional. If the canvas has created a context, it would not make effects.\n * If it is not set, it would be variable based on the current backend.\n */\n contextType?: string;\n /**\n * Optional. A WebGLContextAttributes configuration. If the canvas has created\n * a context, it would not make effects.\n */\n contextAttributes?: WebGLContextAttributes;\n}\n\nexport interface DrawOptions {\n /**\n * Optional. An object of options to customize the values of image tensor.\n */\n imageOptions?: ImageOptions;\n /**\n * Optional. An object to configure the context of the canvas to draw to.\n */\n contextOptions?: ContextOptions;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport { getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap } from './kernel_registry';\nimport { TensorInfo } from './tensor_info';\nimport * as log from './log';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataToGPUOptions, GPUData, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {DataId} from './tensor_info';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc = (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 =\n (...inputs: Array) => {\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;\n extraInfo: string | Promise;\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;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\ninterface RegisteredKernelInvocation {\n kernelName: string;\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation {\n forwardFunc: ForwardFunc;\n backwardsFunc: (dy: T, saved: Tensor[]) => {\n [P in keyof I]: () => I[P]\n };\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation(\n kernelInvocation: RegisteredKernelInvocation|\n CustomGradKernelInvocation):\n kernelInvocation is RegisteredKernelInvocation {\n return (kernelInvocation as RegisteredKernelInvocation).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();\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,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise {\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 {\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,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n log.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise {\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, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend) &&\n typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n const refCount = srcBackend.refCount(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId, true);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype, refCount);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy(nameOrFn: string|ScopeFn, fn?: ScopeFn):\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(start: () => void, end: () => void, f: () => T): T {\n start();\n try {\n const res = f();\n end();\n return res;\n } catch (ex) {\n end();\n throw ex;\n }\n }\n\n private static nextTensorId = 0;\n private nextTensorId(): number {\n return Engine.nextTensorId++;\n }\n\n private static nextVariableId = 0;\n private nextVariableId(): number {\n return Engine.nextVariableId++;\n }\n\n /**\n * This method is called instead of the public-facing tensor.clone() when\n * saving a tensor for backwards pass. It makes sure to add the clone\n * operation to the tape regardless of being called inside a kernel\n * execution.\n */\n private clone(x: Tensor): Tensor {\n const y: Tensor = ENGINE.runKernel(Identity,\n {x} as unknown as NamedTensorMap);\n const inputs = {x};\n const grad = (dy: Tensor) => ({\n x: () => {\n const dtype = 'float32';\n const gradInputs = {x: dy};\n const attrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, gradInputs as unknown as NamedTensorMap,\n // tslint:disable-next-line: no-unnecessary-type-assertion\n attrs as unknown as NamedAttrMap) as Tensor;\n }\n });\n const saved: Tensor[] = [];\n this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n return y;\n }\n\n /**\n * Execute a kernel with the given name and return the output tensor.\n *\n * @param kernelName The name of the kernel to execute.\n * @param inputs A map of input names to tensors.\n * @param attrs A map of attribute names to their values. An attribute is a\n * primitive (non-tensor) input to the kernel.\n * @param inputsToSave A list of tensors, inputs to save for the backprop\n * computation.\n * @param outputsToSave A list of booleans, specifying which output to save\n * for the backprop computation. These are booleans since the output\n * tensors are not visible to the user.\n */\n runKernel(\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(\n kernelParams: RegisteredKernelInvocation|\n CustomGradKernelInvocation): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n\n let out: TensorInfo|TensorInfo[];\n\n const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n kernelParams.kernelName :\n this.state.activeScope != null ? this.state.activeScope.name : '';\n\n // Create the kernelFunc from either a registered kernel OR passed in\n // forward/backward functions (used by custom grad). In this context a\n // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n if (isRegisteredKernelInvocation(kernelParams)) {\n const {kernelName, inputs, attrs} = kernelParams;\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const kernel = getKernel(kernelName, this.backendName);\n util.assert(\n kernel != null,\n () => `Cannot find registered kernel '${kernelName}' for backend '${\n this.backendName}'`);\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n\n const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n // todo (yassogba) remove this option (Tensor) when node backend\n // methods have been modularized and they all return tensorInfo.\n // TensorInfos do not have a rank attribute.\n if ((outInfo as Tensor).rank != null) {\n return outInfo as Tensor;\n }\n return this.makeTensorFromTensorInfo(outInfo);\n });\n\n // Save any required inputs and outputs.\n\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since there would be no backprop for these tensors\n // (which would otherwise dispose them).\n if (isTapeOn) {\n const tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const {forwardFunc} = kernelParams;\n // Running a customGrad op.\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n // Scope name is used to print a more helpful error message if needed.\n this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n //\n // Run the kernelFunc. Optionally profiling it.\n //\n const {inputs, attrs} = kernelParams;\n const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n null :\n kernelParams.backwardsFunc;\n\n let kernelProfile: KernelProfile;\n this.scopedRun(\n // Stop recording to a tape when running a kernel.\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelOrScopeName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelOrScopeName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // We return an empty list rather than throw an error because the kernel we\n // are looking up may not actually be relevant to backproping through the\n // overall function\n //\n // See 'does not error if irrelevant (pruned) ops are missing grads' test\n // in gradients_test.ts for an example.\n return [];\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n * @deprecated\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const tensorInfo: TensorInfo = {dataId, shape, dtype};\n return this.makeTensorFromTensorInfo(tensorInfo, backend);\n }\n\n /**\n * Internal method used by backends. Makes a new tensor that is a wrapper\n * around an existing data id in TensorInfo. It doesn't create a new data id,\n * only increments the ref count used in memory tracking.\n */\n makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend):\n Tensor {\n const {dataId, shape, dtype} = tensorInfo;\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n trackTensor(a: Tensor, backend: KernelBackend): void {\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.numBytes += bytes;\n\n if (!this.state.tensorInfo.has(a.dataId)) {\n this.state.numDataBuffers++;\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes\n });\n }\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n // Track the tensor by dataId and increase the refCount for the dataId in the\n // backend.\n // TODO(pyu10055): This is currently used by makeVariable method, to increase\n // refCount on the backend for the dataId. It can potentially be replaced with\n // Identity op indead of calling backend directly.\n incRef(a: Tensor, backend: KernelBackend): void {\n this.trackTensor(a, backend);\n this.backend.incRef(a.dataId);\n }\n\n removeDataId(dataId: DataId, backend: KernelBackend) {\n if (this.state.tensorInfo.has(dataId) &&\n this.state.tensorInfo.get(dataId).backend === backend) {\n this.state.tensorInfo.delete(dataId);\n this.state.numDataBuffers--;\n }\n }\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n this.state.numBytes -= info.bytes;\n }\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n const bytes = a.size * util.bytesPerElement(a.dtype);\n this.state.numBytes -= bytes;\n }\n\n // Remove the reference to dataId if backend dispose the data successfully\n if (info.backend.disposeData(a.dataId)) {\n this.removeDataId(a.dataId, info.backend);\n }\n\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise)):\n Promise {\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(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(\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),\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(f: CustomGradientFunc):\n (...args: Array) => 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 = (_, 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 {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readToGPU(dataId, options);\n }\n\n async time(query: () => void): Promise {\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(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as unknown as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\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 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nlet isMobileMockValue: boolean|undefined;\n\nexport function mockIsMobile(value: boolean|undefined) {\n isMobileMockValue = value;\n}\n\nexport function isMobile(nav?: Navigator): boolean {\n if (isMobileMockValue !== undefined) {\n return isMobileMockValue;\n }\n if (nav || _isNavigatorDefined()) {\n if (!nav) {\n nav = navigator;\n }\n if (nav.product === 'ReactNative') {\n return true;\n }\n\n const a = nav.userAgent || nav.vendor ||\n // tslint:disable-next-line:no-any\n (typeof window !== 'undefined' ? (window as any).opera : '');\n // Use `navigator.userAgentData.mobile` as fallback.\n if (!a) {\n // tslint:disable-next-line:no-any\n const navAny = nav as any;\n return navAny.userAgentData && navAny.userAgentData.mobile;\n }\n // tslint:disable-next-line:max-line-length\n return /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/** Whether this browser is Safari. */\nENV.registerFlag(\n 'IS_SAFARI',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Safari/.test(navigator.userAgent) &&\n /Apple/.test(navigator.vendor));\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n\n/** Whether to check computation result for errors. */\nENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => ENV.getBool('DEBUG'));\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);\n\n/** Whether to enable canvas2d willReadFrequently for GPU backends */\nENV.registerFlag('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU', () => false);\n\n/** Whether to use setTimeoutCustom */\nENV.registerFlag('USE_SETTIMEOUTCUSTOM', () => false);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {getGlobalTensorClass, Tensor} from './tensor';\nimport {DataType, isWebGLData, isWebGPUData, TensorLike, WebGLData, WebGPUData} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\nimport {bytesPerElement} from './util_base';\n\nexport function inferShape(\n val: TensorLike|WebGLData|WebGPUData, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\n }\n\n if (isWebGLData(val)) {\n const usedChannels = val.channels || 'RGBA';\n return [val.height, val.width * usedChannels.length];\n } else if (isWebGPUData(val)) {\n return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];\n }\n if (!Array.isArray(val)) {\n return []; // Scalar.\n }\n const shape: number[] = [];\n\n while (Array.isArray(firstElem) ||\n isTypedArray(firstElem) && dtype !== 'string') {\n shape.push(firstElem.length);\n firstElem = firstElem[0];\n }\n if (Array.isArray(val) &&\n env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n deepAssertShapeConsistency(val, shape, []);\n }\n\n return shape;\n}\n\nfunction deepAssertShapeConsistency(\n val: TensorLike, shape: number[], indices: number[]) {\n indices = indices || [];\n if (!(Array.isArray(val)) && !isTypedArray(val)) {\n assert(\n shape.length === 0,\n () => `Element arr[${indices.join('][')}] is a primitive, ` +\n `but should be an array/TypedArray of ${shape[0]} elements`);\n return;\n }\n assert(\n shape.length > 0,\n () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n `but is an array of ${val.length} elements`);\n assert(\n val.length === shape[0],\n () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n `elements, but has ${val.length} elements`);\n const subShape = shape.slice(1);\n for (let i = 0; i < val.length; ++i) {\n deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n }\n}\n\nfunction assertDtype(\n expectedDtype: DataType|'numeric'|'string_or_numeric',\n actualDType: DataType, argName: string, functionName: string) {\n if (expectedDtype === 'string_or_numeric') {\n return;\n }\n if (expectedDtype == null) {\n throw new Error(`Expected dtype cannot be null.`);\n }\n if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n expectedDtype === 'numeric' && actualDType === 'string') {\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must ` +\n `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n }\n}\n\nexport function convertToTensor(\n x: T|TensorLike, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T {\n if (x instanceof getGlobalTensorClass()) {\n assertDtype(parseAsDtype, x.dtype, argName, functionName);\n return x;\n }\n let inferredDtype = inferDtype(x);\n // If the user expects a bool/int/float, use that info to update the\n // inferredDtype when it is not a string.\n if (inferredDtype !== 'string' &&\n ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n inferredDtype = parseAsDtype as DataType;\n }\n assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n if ((x == null) ||\n (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n typeof x !== 'boolean' && typeof x !== 'string')) {\n const type = x == null ? 'null' : (x as {}).constructor.name;\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must be a ` +\n `Tensor or TensorLike, but got '${type}'`);\n }\n const inferredShape = inferShape(x, inferredDtype);\n if (!isTypedArray(x) && !Array.isArray(x)) {\n x = [x] as number[];\n }\n const skipTypedArray = true;\n const values = inferredDtype !== 'string' ?\n toTypedArray(x, inferredDtype as DataType) :\n flatten(x as string[], [], skipTypedArray) as string[];\n return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray(\n arg: Array, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T[] {\n if (!Array.isArray(arg)) {\n throw new Error(\n `Argument ${argName} passed to ${functionName} must be a ` +\n '`Tensor[]` or `TensorLike[]`');\n }\n const tensors = arg as T[];\n return tensors.map(\n (t, i) =>\n convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (isPromise(result)) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_(real: T|TensorLike, imag: T|TensorLike): T {\n const $real = convertToTensor(real, 'real', 'complex');\n const $imag = convertToTensor(imag, 'imag', 'complex');\n util.assertShapesMatch(\n $real.shape, $imag.shape,\n `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n `must match in call to tf.complex().`);\n\n const inputs: ComplexInputs = {real: $real, imag: $imag};\n return ENGINE.runKernel(Complex, inputs as unknown as NamedTensorMap);\n}\n\nexport const complex = /* @__PURE__ */ op({complex_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {isWebGLData, isWebGPUData, TensorLike, TypedArray, WebGLData, WebGPUData} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike|WebGLData|WebGPUData, shape: number[],\n inferredShape: number[], dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n } else if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n\n if (isWebGPUData(values) || isWebGLData(values)) {\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new Error(\n `Creating tensor from GPU data only supports ` +\n `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n }\n return ENGINE.backend.createTensorFromGPUData(\n values, shape || inferredShape, dtype);\n }\n\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n // Verify that the shape matches the inferred shape.\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap, WebGLData, WebGPUData} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * ```js\n * // Pass a `WebGLData` object and specify a shape yourself.\n *\n * // This makes it possible for TF.js applications to avoid GPU / CPU sync.\n * // For example, if your application includes a preprocessing step on the GPU,\n * // you could upload the GPU output directly to TF.js, rather than first\n * // downloading the values.\n *\n * // Example for WebGL2:\n * if (tf.findBackend('custom-webgl') == null) {\n * const customCanvas = document.createElement('canvas');\n * const customBackend = new tf.MathBackendWebGL(customCanvas);\n * tf.registerBackend('custom-webgl', () => customBackend);\n * }\n * const savedBackend = tf.getBackend();\n * await tf.setBackend('custom-webgl');\n * const gl = tf.backend().gpgpu.gl;\n * const texture = gl.createTexture();\n * const tex2d = gl.TEXTURE_2D;\n * const width = 2;\n * const height = 2;\n *\n * gl.bindTexture(tex2d, texture);\n * gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n * gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n * gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n * gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n * gl.texImage2D(\n * tex2d, 0, gl.RGBA32F, // internalFormat\n * width, height, 0,\n * gl.RGBA, // textureFormat\n * gl.FLOAT, // textureType\n * new Float32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])\n * );\n *\n * // Currently, the `texture` has 4 pixels:\n * // Pixel0 is {R:0, G:1, B:2, A:3}\n * // Pixel1 is {R:4, G:5, B:6, A:7}\n * // Pixel2 is {R:8, G:9, B:10, A:11}\n * // Pixel3 is {R:12, G:13, B:14, A:15}\n *\n * const logicalShape = [height * width * 2];\n * const a = tf.tensor({texture, height, width, channels: 'BR'}, logicalShape);\n * a.print();\n * // Tensor value will be [2, 0, 6, 4, 10, 8, 14, 12], since [2, 0] is the\n * // values of 'B' and 'R' channels of Pixel0, [6, 4] is the values of 'B' and\n * 'R'\n * // channels of Pixel1...\n *\n * // For postprocessing on the GPU, it's possible to retrieve the texture\n * // backing any tensor by calling the tensor's `dataToGPU` method like\n * // so:\n *\n * const tex = a.dataToGPU();\n * await tf.setBackend(savedBackend);\n * ```\n *\n * ```js\n * // Pass a `WebGPUData` object and specify a shape yourself.\n *\n * // This makes it possible for TF.js applications to avoid GPU / CPU sync.\n * // For example, if your application includes a preprocessing step on the GPU,\n * // you could upload the GPU output directly to TF.js, rather than first\n * // downloading the values. Unlike WebGL, this optionally supports zero copy\n * // by WebGPUData.zeroCopy. When zeroCopy is false or undefined(default), this\n * // passing GPUBuffer can be destroyed after tensor is created. When zeroCopy\n * // is true, this GPUBuffer is bound directly by the tensor, so do not destroy\n * // this GPUBuffer until all access is done.\n *\n * // Example for WebGPU:\n * function createGPUBufferFromData(device, data, dtype) {\n * const bytesPerElement = 4;\n * const sizeInBytes = data.length * bytesPerElement;\n *\n * const gpuWriteBuffer = device.createBuffer({\n * mappedAtCreation: true,\n * size: sizeInBytes,\n * usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC\n * });\n * const arrayBuffer = gpuWriteBuffer.getMappedRange();\n * if (dtype === 'float32') {\n * new Float32Array(arrayBuffer).set(data);\n * } else if (dtype === 'int32') {\n * new Int32Array(arrayBuffer).set(data);\n * } else {\n * throw new Error(\n * `Creating tensor from GPUBuffer only supports` +\n * `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n * }\n * gpuWriteBuffer.unmap();\n *\n * const gpuReadBuffer = device.createBuffer({\n * mappedAtCreation: false,\n * size: sizeInBytes,\n * usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE |\n * GPUBufferUsage.COPY_SRC\n * });\n *\n * const copyEncoder = device.createCommandEncoder();\n * copyEncoder.copyBufferToBuffer(\n * gpuWriteBuffer, 0, gpuReadBuffer, 0, sizeInBytes);\n * const copyCommands = copyEncoder.finish();\n * device.queue.submit([copyCommands]);\n * gpuWriteBuffer.destroy();\n * return gpuReadBuffer;\n * }\n *\n * const savedBackend = tf.getBackend();\n * await tf.setBackend('webgpu').catch(\n * () => {throw new Error(\n * 'Failed to use WebGPU backend. Please use Chrome Canary to run.')});\n * const dtype = 'float32';\n * const device = tf.backend().device;\n * const aData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n * const bData = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4];\n * const expected = [2, 4, 6, 8, 6, 8, 10, 12, 10, 12, 14, 16, 14, 16, 18, 20];\n * const aBuffer = createGPUBufferFromData(device, aData, dtype);\n * const shape = [aData.length];\n * // To use zeroCopy, use {buffer: aBuffer, zeroCopy: true} instead and destroy\n * // aBuffer untill all access is done.\n * const a = tf.tensor({buffer: aBuffer}, shape, dtype);\n * const b = tf.tensor(bData, shape, dtype);\n * const result = tf.add(a, b);\n * result.print();\n * a.dispose();\n * b.dispose();\n * result.dispose();\n * aBuffer.destroy();\n * await tf.setBackend(savedBackend);\n * ```\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`, or a `WebGLData` object, or a\n * `WebGPUData` object. If the values are strings, they will be encoded as utf-8\n * and kept as `Uint8Array[]`. If the values is a `WebGLData` object, the dtype\n * could only be 'float32' or 'int32' and the object has to have: 1. texture, a\n * `WebGLTexture`, the texture must share the same `WebGLRenderingContext` with\n * TFJS's WebGL backend (you could create a custom WebGL backend from your\n * texture's canvas) and the internal texture format for the input texture must\n * be floating point or normalized integer; 2. height, the height of the\n * texture; 3. width, the width of the texture; 4. channels, a non-empty subset\n * of 'RGBA', indicating the values of which channels will be passed to the\n * tensor, such as 'R' or 'BR' (The order of the channels affect the order of\n * tensor values. ). (If the values passed from texture is less than the tensor\n * size, zeros will be padded at the rear.). If the values is a `WebGPUData`\n * object, the dtype could only be 'float32' or 'int32 and the object has to\n * have: buffer, a `GPUBuffer`. The buffer must: 1. share the same `GPUDevice`\n * with TFJS's WebGPU backend; 2. buffer.usage should at least support\n * GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC; 3. buffer.size should not\n * be smaller than the byte size of tensor shape. WebGPUData optionally supports\n * zero copy by flag zeroCopy. When zeroCopy is false or undefined(default),\n * this passing GPUBuffer can be destroyed after tensor is created. When\n * zeroCopy is true, this GPUBuffer is bound directly by the tensor, so do not\n * destroy this GPUBuffer until all access is done.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor(\n values: TensorLike|WebGLData|WebGPUData, shape?: ShapeMap[R],\n dtype?: DataType): Tensor {\n const inferredShape = inferShape(values, dtype);\n return makeTensor(values, shape, inferredShape, dtype) as 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\n/* Type definitions for exporting and importing of models. */\n\n/**\n * A map from Tensor dtype to number of bytes per element of the Tensor.\n */\nexport const DTYPE_VALUE_SIZE_MAP: {[dtype: string]: number} = {\n 'float32': 4,\n 'float16': 2,\n 'int32': 4,\n 'uint16': 2,\n 'uint8': 1,\n 'bool': 1,\n 'complex64': 8\n};\n\n/**\n * A weight manifest.\n *\n * The weight manifest consists of an ordered list of weight-manifest groups.\n * Each weight-manifest group (\"group\" for short hereafter) consists of a\n * number of weight values stored in a number of paths.\n * See the documentation of `WeightManifestGroupConfig` below for more details.\n */\nexport declare type WeightsManifestConfig = WeightsManifestGroupConfig[];\n\n/**\n * A weight-manifest group.\n *\n * Consists of an ordered list of weight values encoded in binary format,\n * stored in an ordered list of paths.\n */\nexport declare interface WeightsManifestGroupConfig {\n /**\n * An ordered list of paths.\n *\n * Paths are intentionally abstract in order to be general. For example, they\n * can be relative URL paths or relative paths on the file system.\n */\n paths: string[];\n\n /**\n * Specifications of the weights stored in the paths.\n */\n weights: WeightsManifestEntry[];\n}\n\n/**\n * Group to which the weight belongs.\n *\n * - 'optimizer': Weight from a stateful optimizer.\n */\nexport type WeightGroup = 'model'|'optimizer';\n\n/**\n * An entry in the weight manifest.\n *\n * The entry contains specification of a weight.\n */\nexport declare interface WeightsManifestEntry {\n /**\n * Name of the weight, e.g., 'Dense_1/bias'\n */\n name: string;\n\n /**\n * Shape of the weight.\n */\n shape: number[];\n\n /**\n * Data type of the weight.\n */\n dtype: 'float32'|'int32'|'bool'|'string'|'complex64';\n\n /**\n * Type of the weight.\n *\n * Optional.\n *\n * The value 'optimizer' indicates the weight belongs to an optimizer\n * (i.e., used only during model training and not during inference).\n */\n group?: WeightGroup;\n\n /**\n * Information for dequantization of the weight.\n */\n quantization?: {\n scale?: number, // The scaling constant to multiply by.\n min?: number, // The (possibly nudged) minimum weight to add.\n dtype: 'uint16'|'uint8'|'float16' // The dtype of the quantized weights.\n };\n}\n\n/**\n * Options for saving a model.\n * @innamespace io\n */\nexport interface SaveConfig {\n /**\n * Whether to save only the trainable weights of the model, ignoring the\n * non-trainable ones.\n */\n trainableOnly?: boolean;\n\n /**\n * Whether the optimizer will be saved (if exists).\n *\n * Default: `false`.\n */\n includeOptimizer?: boolean;\n}\n\n/**\n * Result of a saving operation.\n */\nexport interface SaveResult {\n /**\n * Information about the model artifacts saved.\n */\n modelArtifactsInfo: ModelArtifactsInfo;\n\n /**\n * HTTP responses from the server that handled the model-saving request (if\n * any). This is applicable only to server-based saving routes.\n */\n responses?: Response[];\n\n /**\n * Error messages and related data (if any).\n */\n errors?: Array<{}|string>;\n}\n\nexport declare interface ModelArtifactsInfo {\n /**\n * Timestamp for when the model is saved.\n */\n dateSaved: Date;\n\n /**\n * TODO (cais,yassogba) consider removing GraphDef as GraphDefs now\n * come in a JSON format and none of our IOHandlers support a non json\n * format. We could conder replacing this with 'Binary' if we want to\n * allow future handlers to save to non json formats (though they will\n * probably want more information than 'Binary').\n * Type of the model topology\n *\n * Type of the model topology\n *\n * Possible values:\n * - JSON: JSON config (human-readable, e.g., Keras JSON).\n * - GraphDef: TensorFlow\n * [GraphDef](https://www.tensorflow.org/extend/tool_developers/#graphdef)\n * protocol buffer (binary).\n */\n modelTopologyType: 'JSON'|'GraphDef';\n\n /**\n * Size of model topology (Keras JSON or GraphDef), in bytes.\n */\n modelTopologyBytes?: number;\n\n /**\n * Size of weight specification or manifest, in bytes.\n */\n weightSpecsBytes?: number;\n\n /**\n * Size of weight value data, in bytes.\n */\n weightDataBytes?: number;\n}\n\n/** Model training configuration. */\nexport declare interface TrainingConfig {\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n // See\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tfjs-layers/blob/master/src/keras_format/training_config.ts\n /** Optimizer used for the model training. */\n optimizer_config: {};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Loss function(s) for the model's output(s). */\n loss: string|string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Metric function(s) for the model's output(s). */\n metrics?: string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n weighted_metrics?: string[];\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n sample_weight_mode?: string;\n\n loss_weights?: number[]|{[key: string]: number};\n}\n\nexport type WeightData = ArrayBuffer | ArrayBuffer[];\n\n/**\n * The serialized artifacts of a model, including topology and weights.\n *\n * The `modelTopology`, `trainingConfig`, `weightSpecs` and `weightData` fields\n * of this interface are optional, in order to support topology- or weights-only\n * saving and loading.\n *\n * Note this interface is used internally in IOHandlers. For the file format\n * written to disk as `model.json`, see `ModelJSON`.\n */\nexport declare interface ModelArtifacts {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology?: {}|ArrayBuffer;\n\n /**\n * Serialized configuration for the model's training.\n */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weight specifications.\n *\n * This corresponds to the weightsData below.\n */\n weightSpecs?: WeightsManifestEntry[];\n\n /**\n * Binary buffer(s) for all weight values in the order specified by\n * `weightSpecs`. This may be a single ArrayBuffer of all the weights\n * concatenated together or an Array of ArrayBuffers containing the weights\n * (weights may be sharded across multiple ArrayBuffers).\n */\n weightData?: WeightData;\n\n /**\n * Returns a stream of the weights. Some models are too large to fit in\n * V8's memory heap, and `getWeightStream` loads their weights without storing\n * them all in memory at the same time.\n */\n getWeightStream?: () => ReadableStream;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * Inputs and outputs signature for saved model.\n */\n signature?: {};\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {[key: string]: {}};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n\n /**\n * Inputs and outputs signature for model initializer.\n */\n initializerSignature?: {};\n}\n\n/**\n * The on-disk format of the `model.json` file.\n *\n * TF.js 1.0 always populates the optional fields when writing model.json.\n * Prior versions did not provide those fields.\n */\nexport declare interface ModelJSON {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology: {};\n\n /** Model training configuration. */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weights manifest.\n *\n * The weights manifest consists of an ordered list of weight-manifest\n * groups. Each weight-manifest group consists of a number of weight values\n * stored in a number of paths. See the documentation of\n * `WeightsManifestConfig` for more details.\n */\n weightsManifest: WeightsManifestConfig;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * Inputs and outputs signature for saved model.\n */\n signature?: {};\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {[key: string]: {}};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n\n /**\n * Inputs and outputs signature for model initializer.\n */\n initializerSignature?: {};\n}\n\n/**\n * Type definition for handlers of loading operations.\n */\nexport type LoadHandler = () => Promise;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n Promise;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n save?: SaveHandler;\n load?: LoadHandler;\n}\n\n/**\n * Type definition for handlers of synchronous loading operations.\n */\nexport type LoadHandlerSync = () => ModelArtifacts;\n\n/**\n * Type definition for handlers of synchronous saving operations.\n */\nexport type SaveHandlerSync = (modelArtifact: ModelArtifacts) => SaveResult;\n\n/**\n * Interface for a synchronous model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport type IOHandlerSync = {\n save?: SaveHandlerSync;\n load?: LoadHandlerSync;\n};\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n /**\n * List all models in the model store.\n *\n * @returns A dictionary mapping paths of existing models to their\n * model artifacts info. Model artifacts info include type of the model's\n * topology, byte sizes of the topology, weights, etc.\n */\n listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n /**\n * Remove a model specified by `path`.\n *\n * @param path\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n */\n removeModel(path: string): Promise;\n}\n\n/**\n * Callback for the progress of a long-running action such as an HTTP\n * request for a large binary object.\n *\n * `fraction` should be a number in the [0, 1] interval, indicating how\n * much of the action has completed.\n */\nexport type OnProgressCallback = (fraction: number) => void;\n\n/** @innamespace io */\nexport interface LoadOptions {\n /**\n * RequestInit (options) for HTTP requests.\n *\n * For detailed information on the supported fields, see\n * [https://developer.mozilla.org/en-US/docs/Web/API/Request/Request](\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)\n */\n requestInit?: RequestInit;\n\n /**\n * Progress callback.\n */\n onProgress?: OnProgressCallback;\n\n /**\n * A function used to override the `window.fetch` function.\n */\n fetchFunc?: typeof fetch;\n\n /**\n * Strict loading model: whether extraneous weights or missing\n * weights should trigger an `Error`.\n *\n * If `true`, require that the provided weights exactly match those\n * required by the layers. `false` means that both extra weights\n * and missing weights will be silently ignored.\n *\n * Default: `true`.\n */\n strict?: boolean;\n\n /**\n * Path prefix for weight files, by default this is calculated from the\n * path of the model JSON file.\n *\n * For instance, if the path to the model JSON file is\n * `http://localhost/foo/model.json`, then the default path prefix will be\n * `http://localhost/foo/`. If a weight file has the path value\n * `group1-shard1of2` in the weight manifest, then the weight file will be\n * loaded from `http://localhost/foo/group1-shard1of2` by default. However,\n * if you provide a `weightPathPrefix` value of\n * `http://localhost/foo/alt-weights`, then the weight file will be loaded\n * from the path `http://localhost/foo/alt-weights/group1-shard1of2` instead.\n */\n weightPathPrefix?: string;\n\n /**\n * Whether the module or model is to be loaded from TF Hub.\n *\n * Setting this to `true` allows passing a TF-Hub module URL, omitting the\n * standard model file name and the query parameters.\n *\n * Default: `false`.\n */\n fromTFHub?: boolean;\n\n /**\n * An async function to convert weight file name to URL. The weight file\n * names are stored in model.json's weightsManifest.paths field. By default we\n * consider weight files are colocated with the model.json file. For example:\n * model.json URL: https://www.google.com/models/1/model.json\n * group1-shard1of1.bin url:\n * https://www.google.com/models/1/group1-shard1of1.bin\n *\n * With this func you can convert the weight file name to any URL.\n */\n weightUrlConverter?: (weightFileName: string) => Promise;\n\n /**\n * Whether to stream the model directly to the backend or cache all its\n * weights on CPU first. Useful for large models.\n */\n streamWeights?: boolean;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n /**\n * Is this request for a binary file (as opposed to a json file)\n */\n isBinary?: boolean;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {TypedArray} from '../types';\nimport * as util from '../util';\n\ntype BufferShard = {\n start: number,\n end: number,\n buffer: ArrayBuffer,\n};\n\n/**\n * Wraps a list of ArrayBuffers into a `slice()`-able object without allocating\n * a large ArrayBuffer.\n *\n * Allocating large ArrayBuffers (~2GB) can be unstable on Chrome. TFJS loads\n * its weights as a list of (usually) 4MB ArrayBuffers and then slices the\n * weight tensors out of them. For small models, it's safe to concatenate all\n * the weight buffers into a single ArrayBuffer and then slice the weight\n * tensors out of it, but for large models, a different approach is needed.\n */\n\nexport class CompositeArrayBuffer {\n private shards: BufferShard[] = [];\n private previousShardIndex = 0;\n private bufferUniformSize?: number;\n public readonly byteLength: number;\n\n /**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n * ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n */\n static join(buffers?: ArrayBuffer[] | ArrayBuffer) {\n return new CompositeArrayBuffer(buffers).slice();\n }\n\n constructor(buffers?: ArrayBuffer | ArrayBuffer[] | TypedArray |\n TypedArray[]) {\n if (buffers == null) {\n return;\n }\n // Normalize the `buffers` input to be `ArrayBuffer[]`.\n if (!(buffers instanceof Array)) {\n buffers = [buffers];\n }\n buffers = buffers.map((bufferOrTypedArray) => {\n if (util.isTypedArray(bufferOrTypedArray)) {\n return bufferOrTypedArray.buffer;\n }\n return bufferOrTypedArray;\n });\n\n // Skip setting up shards if there are no buffers.\n if (buffers.length === 0) {\n return;\n }\n\n this.bufferUniformSize = buffers[0].byteLength;\n let start = 0;\n\n for (let i = 0; i < buffers.length; i++) {\n const buffer = buffers[i];\n // Check that all buffers except the last one have the same length.\n if (i !== buffers.length - 1 &&\n buffer.byteLength !== this.bufferUniformSize) {\n // Unset the buffer uniform size, since the buffer sizes are not\n // uniform.\n this.bufferUniformSize = undefined;\n }\n\n // Create the shards, including their start and end points.\n const end = start + buffer.byteLength;\n this.shards.push({ buffer, start, end });\n start = end;\n }\n\n // Set the byteLenghth\n if (this.shards.length === 0) {\n this.byteLength = 0;\n }\n this.byteLength = this.shards[this.shards.length - 1].end;\n }\n\n slice(start = 0, end = this.byteLength): ArrayBuffer {\n // If there are no shards, then the CompositeArrayBuffer was initialized\n // with no data.\n if (this.shards.length === 0) {\n return new ArrayBuffer(0);\n }\n\n // NaN is treated as zero for slicing. This matches ArrayBuffer's behavior.\n start = isNaN(Number(start)) ? 0 : start;\n end = isNaN(Number(end)) ? 0 : end;\n\n // Fix the bounds to within the array.\n start = Math.max(0, start);\n end = Math.min(this.byteLength, end);\n if (end <= start) {\n return new ArrayBuffer(0);\n }\n\n const startShardIndex = this.findShardForByte(start);\n if (startShardIndex === -1) {\n // This should not happen since the start and end indices are always\n // within 0 and the composite array's length.\n throw new Error(`Could not find start shard for byte ${start}`);\n }\n\n const size = end - start;\n const outputBuffer = new ArrayBuffer(size);\n const outputArray = new Uint8Array(outputBuffer);\n let sliced = 0;\n for (let i = startShardIndex; i < this.shards.length; i++) {\n const shard = this.shards[i];\n\n const globalStart = start + sliced;\n const localStart = globalStart - shard.start;\n const outputStart = sliced;\n\n const globalEnd = Math.min(end, shard.end);\n const localEnd = globalEnd - shard.start;\n\n const outputSlice = new Uint8Array(shard.buffer, localStart,\n localEnd - localStart);\n outputArray.set(outputSlice, outputStart);\n sliced += outputSlice.length;\n\n if (end < shard.end) {\n break;\n }\n }\n return outputBuffer;\n }\n\n /**\n * Get the index of the shard that contains the byte at `byteIndex`.\n */\n private findShardForByte(byteIndex: number): number {\n if (this.shards.length === 0 || byteIndex < 0 ||\n byteIndex >= this.byteLength) {\n return -1;\n }\n\n // If the buffers have a uniform size, compute the shard directly.\n if (this.bufferUniformSize != null) {\n this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);\n return this.previousShardIndex;\n }\n\n // If the buffers don't have a uniform size, we need to search for the\n // shard. That means we need a function to check where the byteIndex lies\n // relative to a given shard.\n function check(shard: BufferShard) {\n if (byteIndex < shard.start) {\n return -1;\n }\n if (byteIndex >= shard.end) {\n return 1;\n }\n return 0;\n }\n\n // For efficiency, try the previous shard first.\n if (check(this.shards[this.previousShardIndex]) === 0) {\n return this.previousShardIndex;\n }\n\n // Otherwise, use a generic search function.\n // This should almost never end up being used in practice since the weight\n // entries should always be in order.\n const index = search(this.shards, check);\n if (index === -1) {\n return -1;\n }\n\n this.previousShardIndex = index;\n return this.previousShardIndex;\n }\n}\n\n/**\n * Search for an element of a sorted array.\n *\n * @param sortedArray The sorted array to search\n * @param compare A function to compare the current value against the searched\n * value. Return 0 on a match, negative if the searched value is less than\n * the value passed to the function, and positive if the searched value is\n * greater than the value passed to the function.\n * @returns The index of the element, or -1 if it's not in the array.\n */\nexport function search(sortedArray: T[], compare: (t: T) => number): number {\n // Binary search\n let min = 0;\n let max = sortedArray.length;\n\n while (min <= max) {\n const middle = Math.floor((max - min) / 2) + min;\n const side = compare(sortedArray[middle]);\n\n if (side === 0) {\n return middle;\n } else if (side < 0) {\n max = middle;\n } else {\n min = middle + 1;\n }\n }\n return -1;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n env().set('DEPRECATION_WARNINGS_ENABLED', false);\n console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n console.warn(\n msg + ' You can disable deprecation warnings with ' +\n 'tf.disableDeprecationWarnings().');\n }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n * (undisposed) at this time, which is ≤ the number of tensors\n * (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n * data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n * `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n * `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n * this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n * const x = tf.tensor1d([1, 2, 3]);\n * let x2 = x.square();\n * x2.dispose();\n * x2 = x.square();\n * x2.dispose();\n * return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise)):\n Promise {\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(\n nameOrFn: string|ScopeFn, fn?: ScopeFn): 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(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 {\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 {\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 {\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 {\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,\n priority = 1): boolean {\n return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n env().setPlatform(platformName, platform);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightData, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {Tensor} from '../tensor';\nimport {backend} from '../globals';\nimport {DataId} from '../tensor_info';\nimport {env} from '../environment';\nimport {getBackend} from '../globals';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array> = [];\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(async resolve => {\n const vals = await t.bytes() as Uint8Array[];\n const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n NUM_BYTES_STRING_LENGTH * vals.length;\n const bytes = new Uint8Array(totalNumBytes);\n let offset = 0;\n for (let i = 0; i < vals.length; i++) {\n const val = vals[i];\n const bytesOfLength =\n new Uint8Array(new Uint32Array([val.length]).buffer);\n bytes.set(bytesOfLength, offset);\n offset += NUM_BYTES_STRING_LENGTH;\n bytes.set(val, offset);\n offset += val.length;\n }\n resolve(bytes);\n });\n dataPromises.push(utf8bytes);\n } else {\n dataPromises.push(t.data());\n }\n if (group != null) {\n spec.group = group;\n }\n specs.push(spec);\n }\n\n const tensorValues = await Promise.all(dataPromises);\n return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param weightData A flat ArrayBuffer or an array of ArrayBuffers carrying the\n * binary values of the tensors concatenated in the order specified in\n * `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n * whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n * to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n weightData: WeightData,\n specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const compositeBuffer = new CompositeArrayBuffer(weightData);\n const out: NamedTensorMap = {};\n let offset = 0;\n for (const spec of specs) {\n const byteLength = getWeightBytelength(spec, (start, end) => {\n return compositeBuffer.slice(offset + start, offset + end);\n });\n out[spec.name] = decodeWeight(spec, compositeBuffer\n .slice(offset, offset + byteLength));\n offset += byteLength;\n }\n return out;\n}\n\nfunction getWeightBytelength(spec: WeightsManifestEntry,\n slice: (start: number, end: number) => ArrayBuffer): number {\n\n const size = sizeFromShape(spec.shape);\n let bytesPerValue: number;\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n } else if (spec.dtype === 'string') {\n // Can not statically determine string length.\n let byteLength = 0;\n for (let i = 0; i < size; i++) {\n byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(\n slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];\n }\n return byteLength;\n } else {\n bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];\n }\n\n return size * bytesPerValue;\n}\n\nasync function getWeightBytelengthAsync(\n spec: WeightsManifestEntry,\n slice: (start: number, end: number) => Promise\n): Promise {\n\n const size = sizeFromShape(spec.shape);\n let bytesPerValue: number;\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n } else if (spec.dtype === 'string') {\n // Can not statically determine string length.\n let byteLength = 0;\n for (let i = 0; i < size; i++) {\n byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(\n await slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];\n }\n return byteLength;\n } else {\n bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];\n }\n\n return size * bytesPerValue;\n}\n\nfunction decodeWeight(\n spec: WeightsManifestEntry,\n byteBuffer: ArrayBuffer): Tensor {\n\n const name = spec.name;\n const dtype = spec.dtype;\n const shape = spec.shape;\n const size = sizeFromShape(shape);\n let values: TypedArray | string[] | Uint8Array[];\n let offset = 0;\n\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n if (!('min' in quantization && 'scale' in quantization)) {\n throw new Error(\n `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n `doesn't have corresponding metadata min and scale.`);\n }\n } else if (quantization.dtype === 'float16') {\n if (dtype !== 'float32') {\n throw new Error(\n `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n `which only supports weights of type float32 not ${dtype}.`);\n }\n } else {\n throw new Error(\n `Weight ${spec.name} has unknown ` +\n `quantization dtype ${quantization.dtype}. ` +\n `Supported quantization dtypes are: ` +\n `'uint8', 'uint16', and 'float16'.`);\n }\n const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n const quantizedArray = (quantization.dtype === 'uint8') ?\n new Uint8Array(byteBuffer) :\n new Uint16Array(byteBuffer);\n if (dtype === 'float32') {\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n values = new Float32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = v * quantization.scale + quantization.min;\n }\n } else if (quantization.dtype === 'float16') {\n // TODO: This is inefficient. Make getFloat16Decoder efficient.\n const float16Decode = getFloat16Decoder();\n values = float16Decode(quantizedArray as Uint16Array);\n } else {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type float32.`);\n }\n } else if (dtype === 'int32') {\n if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type int32.`);\n }\n values = new Int32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = Math.round(v * quantization.scale + quantization.min);\n }\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * quantizationSizeFactor;\n } else if (dtype === 'string') {\n const size = sizeFromShape(spec.shape);\n values = [];\n for (let i = 0; i < size; i++) {\n const byteLength = new Uint32Array(\n byteBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(\n byteBuffer.slice(offset, offset + byteLength));\n (values as Uint8Array[]).push(bytes);\n offset += byteLength;\n }\n } else {\n const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n if (dtype === 'float32') {\n values = new Float32Array(byteBuffer);\n } else if (dtype === 'int32') {\n values = new Int32Array(byteBuffer);\n } else if (dtype === 'bool') {\n values = new Uint8Array(byteBuffer);\n } else if (dtype === 'complex64') {\n values = new Float32Array(byteBuffer);\n const real = new Float32Array(values.length / 2);\n const image = new Float32Array(values.length / 2);\n for (let i = 0; i < real.length; i++) {\n real[i] = values[i * 2];\n image[i] = values[i * 2 + 1];\n }\n const realTensor = tensor(real, shape, 'float32');\n const imageTensor = tensor(image, shape, 'float32');\n const complexTensor = complex(realTensor, imageTensor);\n realTensor.dispose();\n imageTensor.dispose();\n return complexTensor;\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n return tensor(values, shape, dtype);\n}\n\nasync function readToLength(reader: ReadableStreamDefaultReader,\n initialData: ArrayBuffer,\n length: number): Promise {\n let data = new Uint8Array(initialData);\n\n while (data.byteLength < length) {\n const {done, value} = await reader.read();\n if (done && value == null) {\n const missing = length - data.byteLength;\n throw new Error(`Reader is done but ${missing} bytes are still expected`);\n }\n\n // TODO: Don't create a new array every loop.\n const newData = new Uint8Array(data.length + value.byteLength);\n newData.set(data, 0);\n newData.set(new Uint8Array(value), data.length);\n data = newData;\n }\n\n return data.buffer;\n}\n\nexport async function decodeWeightsStream(\n weightStream: ReadableStream,\n specs: WeightsManifestEntry[]): Promise {\n\n const tensors: NamedTensorMap = {};\n const reader = weightStream.getReader();\n let data = new ArrayBuffer(0);\n\n for (const spec of specs) {\n const byteLength = await getWeightBytelengthAsync(spec,\n async (start, end) => {\n data = await readToLength(reader, data, end);\n return data.slice(start, end);\n });\n data = await readToLength(reader, data, byteLength);\n\n // Slice the tensor out\n const tensorData = data.slice(0, byteLength);\n data = data.slice(byteLength);\n\n const weightTensor = decodeWeight(spec, tensorData);\n tensors[spec.name] = weightTensor;\n\n // TODO(mattsoulanille): Better way to call uploadToGPU.\n // TODO(mattsoulanille): Make this work for webgl too.\n if (getBackend() === 'webgpu') {\n const b = backend();\n\n if ('uploadToGPU' in b &&\n sizeFromShape(weightTensor.shape) >= (env()\n .get('WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD') as number)) {\n (b.uploadToGPU as (dataId: DataId) => void)(weightTensor.dataId);\n }\n }\n }\n\n return tensors;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n // TODO(adarob, cais): Support quantization.\n if (xs === null) {\n throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n }\n\n let totalByteLength = 0;\n\n // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n // can have a different byte length from that of the `TypedArray` itself,\n // for example, when the `TypedArray` is created from an offset in an\n // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n // the `TypedArray` in byte length. If an element of `xs` does not show\n // this property, a new `TypedArray` that satisfy this property will be\n // constructed and pushed into `normalizedXs`.\n const normalizedXs: TypedArray[] = [];\n xs.forEach((x: TypedArray) => {\n totalByteLength += x.byteLength;\n // tslint:disable:no-any\n normalizedXs.push(\n x.byteLength === x.buffer.byteLength ? x :\n new (x.constructor as any)(x));\n if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n x as any instanceof Uint8Array)) {\n throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n }\n // tslint:enable:no-any\n });\n\n const y = new Uint8Array(totalByteLength);\n let offset = 0;\n normalizedXs.forEach((x: TypedArray) => {\n y.set(new Uint8Array(x.buffer), offset);\n offset += x.byteLength;\n });\n\n return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n if (useNodeBuffer) {\n return Buffer.byteLength(str, 'utf8');\n }\n return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n if (useNodeBuffer) {\n return Buffer.from(buffer).toString('base64');\n }\n const buf = new Uint8Array(buffer);\n let s = '';\n for (let i = 0, l = buf.length; i < l; i++) {\n s += String.fromCharCode(buf[i]);\n }\n return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n if (useNodeBuffer) {\n const buf = Buffer.from(str, 'base64');\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const s = atob(str);\n const buffer = new Uint8Array(s.length);\n for (let i = 0; i < s.length; ++i) {\n buffer.set([s.charCodeAt(i)], i);\n }\n return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n * ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n *\n * @deprecated Use tf.io.CompositeArrayBuffer.join() instead.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]\n | ArrayBuffer): ArrayBuffer {\n return CompositeArrayBuffer.join(buffers);\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n const SEPARATOR = '/';\n path = path.trim();\n while (path.endsWith(SEPARATOR)) {\n path = path.slice(0, path.length - 1);\n }\n const items = path.split(SEPARATOR);\n return items[items.length - 1];\n}\n\n/**\n * Create `ModelJSON` from `ModelArtifacts`.\n *\n * @param artifacts Model artifacts, describing the model and its weights.\n * @param manifest Weight manifest, describing where the weights of the\n * `ModelArtifacts` are stored, and some metadata about them.\n * @returns Object representing the `model.json` file describing the model\n * artifacts and weights\n */\nexport function getModelJSONForModelArtifacts(\n artifacts: ModelArtifacts, manifest: WeightsManifestConfig): ModelJSON {\n const result: ModelJSON = {\n modelTopology: artifacts.modelTopology,\n format: artifacts.format,\n generatedBy: artifacts.generatedBy,\n convertedBy: artifacts.convertedBy,\n weightsManifest: manifest\n };\n if (artifacts.signature != null) {\n result.signature = artifacts.signature;\n }\n if (artifacts.userDefinedMetadata != null) {\n result.userDefinedMetadata = artifacts.userDefinedMetadata;\n }\n if (artifacts.modelInitializer != null) {\n result.modelInitializer = artifacts.modelInitializer;\n }\n if (artifacts.initializerSignature != null) {\n result.initializerSignature = artifacts.initializerSignature;\n }\n if (artifacts.trainingConfig != null) {\n result.trainingConfig = artifacts.trainingConfig;\n }\n return result;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file and weights.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param weightSpecs The list of WeightsManifestEntry for the model. Must be\n * passed if the modelJSON has a weightsManifest.\n * @param weightData An ArrayBuffer or array of ArrayBuffers of weight data for\n * the model corresponding to the weights in weightSpecs. Must be passed if\n * the modelJSON has a weightsManifest.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport function getModelArtifactsForJSONSync(\n modelJSON: ModelJSON, weightSpecs?: WeightsManifestEntry[],\n weightData?: WeightData): ModelArtifacts {\n\n const modelArtifacts: ModelArtifacts = {\n modelTopology: modelJSON.modelTopology,\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy\n };\n\n if (modelJSON.trainingConfig != null) {\n modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n }\n if (modelJSON.weightsManifest != null) {\n if (!weightSpecs) {\n throw new Error('modelJSON has weightsManifest but weightSpecs is null');\n }\n if (!weightData) {\n throw new Error('modelJSON has weightsManifest but weightData is null');\n }\n modelArtifacts.weightSpecs = weightSpecs;\n modelArtifacts.weightData = weightData;\n }\n if (modelJSON.signature != null) {\n modelArtifacts.signature = modelJSON.signature;\n }\n if (modelJSON.userDefinedMetadata != null) {\n modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n }\n if (modelJSON.modelInitializer != null) {\n modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n }\n if (modelJSON.initializerSignature != null) {\n modelArtifacts.initializerSignature = modelJSON.initializerSignature;\n }\n\n return modelArtifacts;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n * reads weights from the listed path(s), and returns a Promise of the\n * weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n modelJSON: ModelJSON,\n loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n /* weightSpecs */ WeightsManifestEntry[], WeightData,\n ]>): Promise {\n let weightSpecs: WeightsManifestEntry[] | undefined;\n let weightData: WeightData | undefined;\n\n if (modelJSON.weightsManifest != null) {\n [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);\n }\n\n return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n new CompositeArrayBuffer(modelArtifacts.weightData).byteLength,\n };\n}\n\n/**\n * Concatenate the weights stored in a WeightsManifestConfig into a list of\n * WeightsManifestEntry\n *\n * @param weightsManifest The WeightsManifestConfig to extract weights from.\n * @returns A list of WeightsManifestEntry of the weights in the weightsManifest\n */\nexport function getWeightSpecs(weightsManifest: WeightsManifestConfig):\n WeightsManifestEntry[] {\n const weightSpecs: WeightsManifestEntry[] = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n return weightSpecs;\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise((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 {\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;\n }\n\n async load(): Promise {\n return this.databaseAction(this.modelPath) as Promise;\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 {\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n } else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n } else {\n // Put model into object store.\n\n // Concatenate all the model weights into a single ArrayBuffer. Large\n // models (~1GB) have problems saving if they are not concatenated.\n // TODO(mattSoulanille): Save large models to multiple indexeddb\n // records.\n modelArtifacts.weightData = CompositeArrayBuffer.join(\n modelArtifacts.weightData);\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n let putInfoRequest: IDBRequest;\n try {\n putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n } catch (error) {\n return reject(error);\n }\n let modelTx: IDBTransaction;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n let putModelRequest: IDBRequest;\n try {\n putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n } catch (error) {\n // Sometimes, the serialized value is too large to store.\n return reject(error);\n }\n putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (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 {\n path = maybeStripScheme(path);\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n const getInfoRequest = infoStore.get(path);\n let modelTx: IDBTransaction;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n } else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () =>\n resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error =>\n reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error(\n 'purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths: string[] = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\n\ntype LocalStorageKeys = {\n /** Key of the localStorage entry storing `ModelArtifactsInfo`. */\n info: string,\n /**\n * Key of the localStorage entry storing the 'modelTopology' key of\n * `model.json`\n */\n topology: string,\n /**\n * Key of the localStorage entry storing the `weightsManifest.weights` entries\n * of `model.json`\n */\n weightSpecs: string,\n /** Key of the localStorage entry storing the weight data in Base64 */\n weightData: string,\n /**\n * Key of the localStorage entry storing the remaining fields of `model.json`\n * @see {@link ModelMetadata}\n */\n modelMetadata: string,\n};\n\ntype ModelMetadata = Omit;\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 {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n\n // TODO(mattsoulanille): Support saving models over 2GB that exceed\n // Chrome's ArrayBuffer size limit.\n const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(\n this.keys.weightData,\n arrayBufferToBase64String(weightBuffer));\n\n // Note that JSON.stringify doesn't write out keys that have undefined\n // values, so for some keys, we set undefined instead of a null-ish\n // value.\n const metadata: Required = {\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n signature: modelArtifacts.signature != null ?\n modelArtifacts.signature :\n undefined,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ?\n modelArtifacts.userDefinedMetadata :\n undefined,\n modelInitializer: modelArtifacts.modelInitializer != null ?\n modelArtifacts.modelInitializer :\n undefined,\n initializerSignature: modelArtifacts.initializerSignature != null ?\n modelArtifacts.initializerSignature :\n undefined,\n trainingConfig: modelArtifacts.trainingConfig != null ?\n modelArtifacts.trainingConfig :\n undefined\n };\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));\n\n return {modelArtifactsInfo};\n } catch (err) {\n // If saving failed, clean up all items saved so far.\n removeItems(this.keys);\n\n throw new Error(\n `Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load(): Promise {\n const info =\n JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n if (info == null) {\n throw new Error(\n `In local storage, there is no model with name '${this.modelPath}'`);\n }\n\n if (info.modelTopologyType !== 'JSON') {\n throw new Error(\n 'BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n\n const out: ModelArtifacts = {};\n\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(\n `In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(\n `In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString) as ModelMetadata;\n out.format = metadata.format;\n out.generatedBy = metadata.generatedBy;\n out.convertedBy = metadata.convertedBy;\n if (metadata.signature != null) {\n out.signature = metadata.signature;\n }\n if (metadata.userDefinedMetadata != null) {\n out.userDefinedMetadata = metadata.userDefinedMetadata;\n }\n if (metadata.modelInitializer != null) {\n out.modelInitializer = metadata.modelInitializer;\n }\n if (metadata.initializerSignature != null) {\n out.initializerSignature = metadata.initializerSignature;\n }\n if (metadata.trainingConfig != null) {\n out.trainingConfig = metadata.trainingConfig;\n }\n }\n\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(\n `In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n return out;\n }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(\n url.slice(BrowserLocalStorage.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n private readonly LS: Storage;\n\n constructor() {\n assert(\n env().getBool('IS_BROWSER'),\n () => 'Current environment is not a web browser');\n assert(\n typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined',\n () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n }\n }\n return out;\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n removeItems(keys);\n return info;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = ModelStoreManagerRegistry.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(ModelStoreManagerRegistry.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a registered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise {\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 {\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 {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\nimport {isTypedArrayBrowser} from './is_typed_array_browser';\n\nexport class PlatformBrowser implements Platform {\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n private textEncoder: TextEncoder;\n\n // For setTimeoutCustom\n private readonly messageName = 'setTimeoutCustom';\n private functionRefs: Function[] = [];\n private handledMessageCount = 0;\n private hasEventListener = false;\n\n fetch(path: string, init?: RequestInit): Promise {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n\n // If the setTimeout nesting level is greater than 5 and timeout is less\n // than 4ms, timeout will be clamped to 4ms, which hurts the perf.\n // Interleaving window.postMessage and setTimeout will trick the browser and\n // avoid the clamp.\n setTimeoutCustom(functionRef: Function, delay: number): void {\n if (typeof window === 'undefined' ||\n !env().getBool('USE_SETTIMEOUTCUSTOM')) {\n setTimeout(functionRef, delay);\n return;\n }\n\n this.functionRefs.push(functionRef);\n setTimeout(() => {\n window.postMessage(\n {name: this.messageName, index: this.functionRefs.length - 1}, '*');\n }, delay);\n\n if (!this.hasEventListener) {\n this.hasEventListener = true;\n window.addEventListener('message', (event: MessageEvent) => {\n if (event.source === window && event.data.name === this.messageName) {\n event.stopPropagation();\n const functionRef = this.functionRefs[event.data.index];\n functionRef();\n this.handledMessageCount++;\n if (this.handledMessageCount === this.functionRefs.length) {\n this.functionRefs = [];\n this.handledMessageCount = 0;\n }\n }\n }, true);\n }\n }\n\n isTypedArray(a: unknown): a is Uint8Array | Float32Array | Int32Array\n | Uint8ClampedArray {\n return isTypedArrayBrowser(a);\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise;\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 {\n if (env().global.fetch != null) {\n return env().global.fetch(path, requestInits);\n }\n\n if (systemFetch == null) {\n systemFetch = getNodeFetch.importFetch();\n }\n return systemFetch(path, requestInits);\n }\n\n now(): number {\n const time = process.hrtime();\n return time[0] * 1000 + time[1] / 1000000;\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Node built-in encoder only supports utf-8, but got ${encoding}`);\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n if (bytes.length === 0) {\n return '';\n }\n return new this.util.TextDecoder(encoding).decode(bytes);\n }\n isTypedArray(a: unknown): a is Float32Array | Int32Array | Uint8Array\n | Uint8ClampedArray {\n return this.util.types.isFloat32Array(a)\n || this.util.types.isInt32Array(a)\n || this.util.types.isUint8Array(a)\n || this.util.types.isUint8ClampedArray(a);\n }\n}\n\nif (env().get('IS_NODE') && !env().get('IS_BROWSER')) {\n env().setPlatform('node', new PlatformNode());\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer(shape, dtype, values);\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const cast = /* @__PURE__ */ op({cast_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernel(Identity, inputs as unknown as NamedTensorMap);\n}\n\nexport const clone = /* @__PURE__ */ op({clone_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Add, AddInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print(); // or tf.add(a, b)\n * ```\n *\n * ```js\n * // Broadcast add a with b.\n * const a = tf.scalar(5);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print(); // or tf.add(a, b)\n * ```\n * @param a The first `tf.Tensor` to add.\n * @param b The second `tf.Tensor` to add. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction add_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'add');\n let $b = convertToTensor(b, 'b', 'add');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: AddInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n\nexport const add = /* @__PURE__ */ op({add_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FloorDiv, FloorDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n * The result is rounded with floor function.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.floorDiv(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.floorDiv(b).print(); // or tf.floorDiv(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction floorDiv_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'floorDiv');\n let $b = convertToTensor(b, 'b', 'floorDiv');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: FloorDivInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(FloorDiv, inputs as unknown as NamedTensorMap);\n}\n\nexport const floorDiv = /* @__PURE__ */ op({floorDiv_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RealDiv, RealDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {floorDiv} from './floorDiv';\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.div(b).print(); // or tf.div(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction div_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'div');\n let $b = convertToTensor(b, 'b', 'div');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'int32' && $b.dtype === 'int32') {\n return floorDiv($a, $b);\n }\n\n const inputs: RealDivInputs = {a: $a, b: $b};\n const attrs = {};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(RealDiv,\n inputs as unknown as NamedTensorMap, attrs) as T;\n}\n\nexport const div = /* @__PURE__ */ op({div_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multiply, MultiplyInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.\n *\n * We also expose `tf.mulStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([2, 3, 4, 5]);\n *\n * a.mul(b).print(); // or tf.mul(a, b)\n * ```\n *\n * ```js\n * // Broadcast mul a with b.\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.scalar(5);\n *\n * a.mul(b).print(); // or tf.mul(a, b)\n * ```\n * @param a The first tensor to multiply.\n * @param b The second tensor to multiply. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mul_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'mul');\n let $b = convertToTensor(b, 'b', 'mul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: MultiplyInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Multiply, inputs as unknown as NamedTensorMap);\n}\nexport const mul = /* @__PURE__ */ op({mul_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sqrt', 'float32');\n\n const inputs: SqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Sqrt, inputs as unknown as NamedTensorMap);\n}\nexport const sqrt = /* @__PURE__ */ op({sqrt_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Computes square of `x` element-wise: `x ^ 2`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);\n *\n * x.square().print(); // or tf.square(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction square_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'square');\n const attrs = {};\n return ENGINE.runKernel('Square', {x: $x}, attrs);\n}\n\nexport const square = /* @__PURE__ */ op({square_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'zerosLike');\n const inputs: ZerosLikeInputs = {x: $x};\n return ENGINE.runKernel(ZerosLike, inputs as unknown as NamedTensorMap);\n}\nexport const zerosLike = /* @__PURE__ */ op({zerosLike_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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, 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(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(f: (...args: Tensor[]) => O): (\n args: Tensor[], dy?: O) => {\n grads: Tensor[];\n value: O;\n} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in valueAndGrads(f) must be a function');\n return (args: Tensor[], dy?: O) => {\n util.assert(\n Array.isArray(args) && args.every(arg => arg instanceof Tensor),\n () => 'The args passed in valueAndGrads(f)(args) must be array of ' +\n 'tensors');\n util.assert(\n dy == null || dy instanceof Tensor,\n () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');\n const res = ENGINE.gradients(() => f(...args), args, dy);\n if (dy != null) {\n util.assertShapesMatch(\n res.value.shape, dy.shape,\n 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +\n 'match the shape returned by f([x1,...])');\n }\n checkGrads(res.grads);\n return res;\n };\n}\n\n/**\n * Computes and returns the gradient of f(x) with respect to the list of\n * trainable variables provided by `varList`. If no list is provided, it\n * defaults to all trainable variables.\n *\n * ```js\n * const a = tf.variable(tf.tensor1d([3, 4]));\n * const b = tf.variable(tf.tensor1d([5, 6]));\n * const x = tf.tensor1d([1, 2]);\n *\n * // f(a, b) = a * x ^ 2 + b * x\n * const f = () => a.mul(x.square()).add(b.mul(x)).sum();\n * // df/da = x ^ 2, df/db = x\n * const {value, grads} = tf.variableGrads(f);\n *\n * Object.keys(grads).forEach(varName => grads[varName].print());\n * ```\n *\n * @param f The function to execute. f() should return a scalar.\n * @param varList The list of variables to compute the gradients with respect\n * to. Defaults to all trainable variables.\n * @returns An object with the following keys and values:\n * - `value`: The value of the function `f`.\n * - `grads`: A map from the names of the variables to the gradients.\n * If the `varList` argument is provided explicitly and contains a subset of\n * non-trainable variables, this map in the return value will contain keys\n * that map the names of the non-trainable variables to `null`.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction variableGrads(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in variableGrads(f) must be a function');\n util.assert(\n varList == null ||\n Array.isArray(varList) && varList.every(v => v instanceof Variable),\n () =>\n 'The varList passed in variableGrads(f, varList) must be an array ' +\n 'of variables');\n\n const specifiedVarList = varList != null;\n if (!specifiedVarList) {\n // Get all of the trainable variables.\n varList = [];\n for (const varName in ENGINE.registeredVariables) {\n varList.push(ENGINE.registeredVariables[varName]);\n }\n }\n\n const specifiedNonTrainable: Variable[] =\n specifiedVarList ? varList.filter(variable => !variable.trainable) : null;\n\n // Prune non-trainable variables.\n const originalVarCount = varList.length;\n varList = varList.filter(variable => variable.trainable);\n util.assert(\n varList.length > 0,\n () => `variableGrads() expects at least one of the input variables to ` +\n `be trainable, but none of the ${originalVarCount} variables is ` +\n `trainable.`);\n\n const allowNoGradients = true;\n const {value, grads} = ENGINE.gradients(f, varList, null, allowNoGradients);\n\n util.assert(\n grads.some(g => g != null),\n () => 'Cannot find a connection between any variable and the result of ' +\n 'the loss function y=f(x). Please make sure the operations that ' +\n 'use variables are inside the function f passed to minimize().');\n util.assert(\n value.rank === 0,\n () => `The f passed in variableGrads(f) must return a scalar, but it ` +\n `returned a rank-${value.rank} tensor`);\n\n const namedGrads: NamedTensorMap = {};\n varList.forEach((v, i) => {\n if (grads[i] != null) {\n namedGrads[v.name] = grads[i];\n }\n });\n if (specifiedNonTrainable != null) {\n // If varList is explicitly provided and contains non-trainable values,\n // add them to the returned gradients with `null` values.\n specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);\n }\n return {value, grads: namedGrads};\n}\n\n/**\n * Overrides the gradient computation of a function `f`.\n *\n * Takes a function\n * `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`\n * and returns another function `g(...inputs)` which takes the same inputs as\n * `f`. When called, `g` returns `f().value`. In backward mode, custom gradients\n * with respect to each input of `f` are computed using `f().gradFunc`.\n *\n * The `save` function passed to `f` should be used for saving tensors needed\n * in the gradient. And the `saved` passed to the `gradFunc` is a\n * `NamedTensorMap`, which contains those saved tensors.\n *\n * ```js\n * const customOp = tf.customGrad((x, save) => {\n * // Save x to make sure it's available later for the gradient.\n * save([x]);\n * // Override gradient of our custom x ^ 2 op to be dy * abs(x);\n * return {\n * value: x.square(),\n * // Note `saved.x` which points to the `x` we saved earlier.\n * gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]\n * };\n * });\n *\n * const x = tf.tensor1d([-1, -2, 3]);\n * const dx = tf.grad(x => customOp(x));\n *\n * console.log(`f(x):`);\n * customOp(x).print();\n * console.log(`f'(x):`);\n * dx(x).print();\n * ```\n *\n * @param f The function to evaluate in forward mode, which should return\n * `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`\n * returns the custom gradients of `f` with respect to its inputs.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction customGrad(f: CustomGradientFunc):\n (...args: Tensor[]) => T {\n return ENGINE.customGrad(f);\n}\n\nfunction checkGrads(grads: Tensor[]) {\n const numNullGradients = grads.filter(g => g == null).length;\n if (numNullGradients > 0) {\n throw new Error(\n `Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.`);\n }\n}\n\nexport {\n customGrad,\n variableGrads,\n valueAndGrad,\n valueAndGrads,\n grad,\n grads,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar} from '../tensor';\nimport {DataType} from '../types';\nimport {isTypedArray} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.scalar` as it makes the code more readable.\n *\n * ```js\n * tf.scalar(3.14).print();\n * ```\n *\n * @param value The value of the scalar.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function scalar(\n value: number|boolean|string|Uint8Array, dtype?: DataType): Scalar {\n if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&\n dtype !== 'complex64') {\n throw new Error(\n 'Error creating a new Scalar: value must be a primitive ' +\n '(number|boolean|string)');\n }\n if (dtype === 'string' && isTypedArray(value) &&\n !(value instanceof Uint8Array)) {\n throw new Error(\n 'When making a scalar from encoded string, ' +\n 'the value must be `Uint8Array`.');\n }\n const shape: number[] = [];\n const inferredShape: number[] = [];\n return makeTensor(value, shape, inferredShape, dtype) as Scalar;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 {}\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 = {\n // tslint:disable-next-line:no-any\n new (...args: any[]): T; className: string; fromConfig: FromConfigMethod;\n};\nexport declare type FromConfigMethod =\n (cls: SerializableConstructor, config: ConfigDict) => T;\n\n/**\n * Maps to mapping between the custom object and its name.\n *\n * After registering a custom class, these two maps will add key-value pairs\n * for the class object and the registered name.\n *\n * Therefore we can get the relative registered name by calling\n * getRegisteredName() function.\n *\n * For example:\n * GLOBAL_CUSTOM_OBJECT: {key=registeredName: value=corresponding\n * CustomObjectClass}\n *\n * GLOBAL_CUSTOM_NAMES: {key=CustomObjectClass: value=corresponding\n * registeredName}\n *\n */\nconst GLOBAL_CUSTOM_OBJECT =\n new Map>();\n\nconst GLOBAL_CUSTOM_NAMES =\n new Map, string>();\n\n/**\n * Serializable defines the serialization contract.\n *\n * TFJS requires serializable classes to return their className when asked\n * to avoid issues with minification.\n */\nexport abstract class Serializable {\n /**\n * Return the class name for this class to use in serialization contexts.\n *\n * Generally speaking this will be the same thing that constructor.name\n * would have returned. However, the class name needs to be robust\n * against minification for serialization/deserialization to work properly.\n *\n * There's also places such as initializers.VarianceScaling, where\n * implementation details between different languages led to different\n * class hierarchies and a non-leaf node is used for serialization purposes.\n */\n getClassName(): string {\n return (this.constructor as SerializableConstructor)\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(\n cls: SerializableConstructor, 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, FromConfigMethod]\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(cls: SerializableConstructor) {\n SerializationMap.getMap().classNameMap[cls.className] =\n [cls, cls.fromConfig];\n }\n}\n\n/**\n * Register a class with the serialization map of TensorFlow.js.\n *\n * This is often used for registering custom Layers, so they can be\n * serialized and deserialized.\n *\n * Example 1. Register the class without package name and specified name.\n *\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n * static className = 'MyCustomLayer';\n *\n * constructor(config) {\n * super(config);\n * }\n * }\n * tf.serialization.registerClass(MyCustomLayer);\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT.get(\"Custom>MyCustomLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));\n * ```\n *\n * Example 2. Register the class with package name: \"Package\" and specified\n * name: \"MyLayer\".\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n * static className = 'MyCustomLayer';\n *\n * constructor(config) {\n * super(config);\n * }\n * }\n * tf.serialization.registerClass(MyCustomLayer, \"Package\", \"MyLayer\");\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT.get(\"Package>MyLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));\n * ```\n *\n * Example 3. Register the class with specified name: \"MyLayer\".\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n * static className = 'MyCustomLayer';\n *\n * constructor(config) {\n * super(config);\n * }\n * }\n * tf.serialization.registerClass(MyCustomLayer, undefined, \"MyLayer\");\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT.get(\"Custom>MyLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));\n * ```\n *\n * Example 4. Register the class with specified package name: \"Package\".\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n * static className = 'MyCustomLayer';\n *\n * constructor(config) {\n * super(config);\n * }\n * }\n * tf.serialization.registerClass(MyCustomLayer, \"Package\");\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT\n * .get(\"Package>MyCustomLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES\n * .get(MyCustomLayer));\n * ```\n *\n * @param cls The class to be registered. It must have a public static member\n * called `className` defined and the value must be a non-empty string.\n * @param pkg The pakcage name that this class belongs to. This used to define\n * the key in GlobalCustomObject. If not defined, it defaults to `Custom`.\n * @param name The name that user specified. It defaults to the actual name of\n * the class as specified by its static `className` property.\n * @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true}\n */\nexport function registerClass(\n cls: SerializableConstructor, pkg?: string, name?: string) {\n assert(\n cls.className != null,\n () => `Class being registered does not have the static className ` +\n `property defined.`);\n assert(\n typeof cls.className === 'string',\n () => `className is required to be a string, but got type ` +\n typeof cls.className);\n assert(\n cls.className.length > 0,\n () => `Class being registered has an empty-string as its className, ` +\n `which is disallowed.`);\n\n if (typeof pkg === 'undefined') {\n pkg = 'Custom';\n }\n\n if (typeof name === 'undefined') {\n name = cls.className;\n }\n\n const className = name;\n const registerName = pkg + '>' + className;\n\n SerializationMap.register(cls);\n GLOBAL_CUSTOM_OBJECT.set(registerName, cls);\n GLOBAL_CUSTOM_NAMES.set(cls, registerName);\n\n return cls;\n}\n\n/**\n * Get the registered name of a class. If the class has not been registered,\n * return the class name.\n *\n * @param cls The class we want to get register name for. It must have a public\n * static member called `className` defined.\n * @returns registered name or class name.\n */\nexport function getRegisteredName(\n cls: SerializableConstructor) {\n if (GLOBAL_CUSTOM_NAMES.has(cls)) {\n return GLOBAL_CUSTOM_NAMES.get(cls);\n } else {\n return cls.className;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {dispose} from '../globals';\nimport {variableGrads} from '../gradients';\nimport {scalar} from '../ops/ops';\nimport {Serializable} from '../serialization';\nimport {Scalar, Variable} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\n/**\n * A variable that belongs to an optimizer.\n *\n * The `originalName` field is required for keeping track of the canonical\n * name of the variable, which is usually the name of the model weight that\n * the variable is related to plus a suffix, e.g., 'dense1/kernel/momentum'.\n * The name of the `Variable` object itself cannot be used directly due to\n * possible deduplication: Every `Variable` must have a unique name but more\n * than one optimizer objects of the same type may be created for the same model\n * or the same `Variable`.\n */\nexport interface OptimizerVariable {\n originalName: string;\n variable: Variable;\n}\n\n/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */\nexport abstract class Optimizer extends Serializable {\n protected iterations_: number;\n\n /**\n * Executes `f()` and minimizes the scalar output of `f()` by computing\n * gradients of y with respect to the list of trainable variables provided by\n * `varList`. If no list is provided, it defaults to all trainable variables.\n *\n * @param f The function to execute and whose output to minimize.\n * @param returnCost Whether to return the scalar cost value produced by\n * executing `f()`.\n * @param varList An optional list of variables to update. If specified, only\n * the trainable variables in varList will be updated by minimize. Defaults to\n * all trainable variables.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n minimize(f: () => Scalar, returnCost = false, varList?: Variable[]): Scalar\n |null {\n const {value, grads} = this.computeGradients(f, varList);\n\n if (varList != null) {\n const gradArray: NamedTensor[] =\n varList.map(v => ({name: v.name, tensor: grads[v.name]}));\n this.applyGradients(gradArray);\n } else {\n this.applyGradients(grads);\n }\n\n // Dispose gradients.\n dispose(grads);\n\n if (returnCost) {\n return value;\n } else {\n value.dispose();\n return null;\n }\n }\n\n /**\n * The number of iterations that this optimizer instance has been invoked for.\n */\n get iterations(): number {\n if (this.iterations_ == null) {\n this.iterations_ = 0;\n }\n return this.iterations_;\n }\n\n protected incrementIterations() {\n this.iterations_ = this.iterations + 1;\n }\n\n /**\n * Executes f() and computes the gradient of the scalar output of f() with\n * respect to the list of trainable variables provided by `varList`. If no\n * list is provided, it defaults to all trainable variables.\n *\n * @param f The function to execute and whose output to use for computing\n * gradients with respect to variables.\n * @param varList An optional list of variables to compute gradients with\n * respect to. If specified, only the trainable variables in varList will have\n * gradients computed with respect to. Defaults to all trainable variables.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n computeGradients(f: () => Scalar, varList?: Variable[]):\n {value: Scalar, grads: NamedTensorMap} {\n return variableGrads(f, varList);\n }\n\n /**\n * Updates variables by using the computed gradients.\n *\n * @param variableGradients A mapping of variable name to its gradient value.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers'}\n */\n abstract applyGradients(variableGradients: NamedTensorMap|\n NamedTensor[]): void;\n\n /**\n * Dispose the variables (if any) owned by this optimizer instance.\n */\n dispose(): void {\n if (this.iterations_ != null) {\n dispose(this.iterations_);\n }\n }\n\n async saveIterations(): Promise {\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 {\n throw new Error('getWeights() is not implemented for this optimizer yet.');\n }\n\n async setWeights(weightValues: NamedTensor[]): Promise {\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 {\n this.iterations_ = (await weightValues[0].tensor.data())[0];\n return weightValues.slice(1);\n }\n}\n\nObject.defineProperty(Optimizer, Symbol.hasInstance, {\n value: (instance: Optimizer) => {\n return instance.minimize != null && instance.computeGradients != null &&\n instance.applyGradients != null;\n }\n});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/ops';\nimport {square} from '../ops/square';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdadeltaOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adadelta';\n }\n private accumulatedGrads: OptimizerVariable[] = [];\n private accumulatedUpdates: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected rho: number,\n protected epsilon: number = null) {\n super();\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedGrads[i] == null) {\n this.accumulatedGrads[i] = {\n originalName: `${name}/accum_grad`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedUpdates[i] == null) {\n this.accumulatedUpdates[i] = {\n originalName: `${name}/accum_var`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedGrad = this.accumulatedGrads[i].variable;\n const accumulatedUpdate = this.accumulatedUpdates[i].variable;\n\n tidy(() => {\n const newAccumulatedGrad =\n add(mul(accumulatedGrad, this.rho),\n mul(square(gradient), 1 - this.rho));\n\n const updates =\n mul(div(sqrt(add(accumulatedUpdate, this.epsilon)),\n sqrt(add(accumulatedGrad, this.epsilon))),\n gradient);\n\n const newAccumulatedUpdate =\n add(mul(accumulatedUpdate, this.rho),\n mul(square(updates), 1 - this.rho));\n\n accumulatedGrad.assign(newAccumulatedGrad);\n accumulatedUpdate.assign(newAccumulatedUpdate);\n\n const newValue = add(mul(updates, -this.learningRate), value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedUpdates != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n dispose(this.accumulatedUpdates.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedGrads, ...this.accumulatedUpdates];\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n weightValues = await this.extractIterations(weightValues);\n const variableCount = weightValues.length / 2;\n const trainable = false;\n this.accumulatedGrads =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedUpdates =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'rho': this.rho,\n 'epsilon': this.epsilon\n };\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(config['learningRate'], config['rho'], config['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 {ENGINE} from '../engine';\nimport {Fill, FillAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {inferDtype} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\n/**\n * Creates a `tf.Tensor` filled with a scalar value.\n *\n * ```js\n * tf.fill([2, 2], 4).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param value The scalar value to fill the tensor with.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n * 'float32' if the given param value is a number, otherwise 'string'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction fill(\n shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n\n dtype = dtype || inferDtype(value);\n const attrs: FillAttrs = {shape, value, dtype};\n\n return ENGINE.runKernel(Fill, {}, attrs as unknown as NamedAttrMap);\n}\n\nexport {fill};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {fill} from '../ops/fill';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdagradOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adagrad';\n }\n\n private accumulatedGrads: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, private initialAccumulatorValue = 0.1) {\n super();\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n if (this.accumulatedGrads[i] == null) {\n const trainable = false;\n this.accumulatedGrads[i] = {\n originalName: `${name}/accumulator`,\n variable: tidy(\n () => fill(value.shape, this.initialAccumulatorValue)\n .variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedGrad = this.accumulatedGrads[i].variable;\n\n tidy(() => {\n const newAccumulatedGrad = add(accumulatedGrad, square(gradient));\n accumulatedGrad.assign(newAccumulatedGrad);\n\n const newValue = add(\n mul(div(gradient,\n sqrt(add(newAccumulatedGrad, ENGINE.backend.epsilon()))),\n -this.learningRate),\n value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedGrads != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise {\n // Order matters for Python compatibility.\n return [await this.saveIterations()].concat(this.accumulatedGrads.map(\n v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n weightValues = await this.extractIterations(weightValues);\n const trainable = false;\n this.accumulatedGrads = weightValues.map(\n v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'initialAccumulatorValue': this.initialAccumulatorValue,\n };\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(config['learningRate'], config['initialAccumulatorValue']);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(\n base: Tensor|TensorLike, exp: Tensor|TensorLike): T {\n let $base = convertToTensor(base, 'base', 'pow');\n let $exp = convertToTensor(exp, 'exp', 'pow');\n [$base, $exp] = makeTypesMatch($base, $exp);\n\n const inputs: PowInputs = {a: $base, b: $exp};\n\n return ENGINE.runKernel(Pow, inputs as unknown as NamedTensorMap);\n}\n\nexport const pow = /* @__PURE__ */ op({pow_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'sub');\n let $b = convertToTensor(b, 'b', 'sub');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: SubInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Sub, inputs as unknown as NamedTensorMap);\n}\n\nexport const sub = /* @__PURE__ */ op({sub_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {pow} from '../ops/pow';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adam';\n }\n private accBeta1: Variable;\n private accBeta2: Variable;\n\n private accumulatedFirstMoment: OptimizerVariable[] = [];\n private accumulatedSecondMoment: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected beta1: number,\n protected beta2: number, protected epsilon: number = null) {\n super();\n tidy(() => {\n // accB* will be updated by batch.\n this.accBeta1 = scalar(beta1).variable();\n this.accBeta2 = scalar(beta2).variable();\n });\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const varNames = Array.isArray(variableGradients) ?\n variableGradients.map(v => v.name) :\n Object.keys(variableGradients);\n tidy(() => {\n const oneMinusAccBeta1 = sub(1, this.accBeta1);\n const oneMinusAccBeta2 = sub(1, this.accBeta2);\n\n varNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedFirstMoment[i] == null) {\n this.accumulatedFirstMoment[i] = {\n originalName: `${name}/m`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedSecondMoment[i] == null) {\n this.accumulatedSecondMoment[i] = {\n originalName: `${name}/v`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const firstMoment = this.accumulatedFirstMoment[i].variable;\n const secondMoment = this.accumulatedSecondMoment[i].variable;\n\n const newFirstMoment =\n add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n const newSecondMoment =\n add(mul(secondMoment, this.beta2),\n mul(square(gradient), 1 - this.beta2));\n\n const biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);\n const biasCorrectedSecondMoment =\n div(newSecondMoment, oneMinusAccBeta2);\n\n firstMoment.assign(newFirstMoment);\n secondMoment.assign(newSecondMoment);\n\n const newValue =\n add(mul(div(biasCorrectedFirstMoment,\n add(sqrt(biasCorrectedSecondMoment), this.epsilon)),\n -this.learningRate),\n value);\n value.assign(newValue);\n });\n\n this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n this.accBeta2.assign(mul(this.accBeta2, this.beta2));\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.accBeta1.dispose();\n this.accBeta2.dispose();\n\n if (this.accumulatedFirstMoment != null) {\n dispose(this.accumulatedFirstMoment.map(v => v.variable));\n }\n if (this.accumulatedSecondMoment != null) {\n dispose(this.accumulatedSecondMoment.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n weightValues = await this.extractIterations(weightValues);\n tidy(() => {\n this.accBeta1.assign(pow(this.beta1, this.iterations_ + 1));\n this.accBeta2.assign(pow(this.beta2, this.iterations_ + 1));\n });\n\n const variableCount = weightValues.length / 2;\n const trainable = false;\n this.accumulatedFirstMoment =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedSecondMoment =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'beta1': this.beta1,\n 'beta2': this.beta2,\n 'epsilon': this.epsilon,\n };\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['beta1'], config['beta2'],\n config['epsilon']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'abs');\n\n if ($x.dtype === 'complex64') {\n const inputs: ComplexAbsInputs = {x: $x};\n return ENGINE.runKernel(ComplexAbs, inputs as unknown as NamedTensorMap);\n } else {\n const inputs: AbsInputs = {x: $x};\n return ENGINE.runKernel(Abs, inputs as unknown as NamedTensorMap);\n }\n}\n\nexport const abs = /* @__PURE__ */ op({abs_});\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(\n inShape: number[], outShape: number[]): number[] {\n const inRank = inShape.length;\n const dims: number[] = [];\n for (let i = 0; i < inRank; i++) {\n const dim = inRank - 1 - i;\n const a = inShape[dim] || 1;\n const b = outShape[outShape.length - 1 - i] || 1;\n if (b > 1 && a === 1) {\n dims.unshift(dim);\n }\n }\n return dims;\n}\n\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(\n inShape: number[], outShape: number[]): number[] {\n const result: number[] = [];\n for (let i = 0; i < outShape.length; i++) {\n const inDim = inShape[inShape.length - i - 1];\n const outAxis = outShape.length - i - 1;\n const outDim = outShape[outAxis];\n if (inDim == null || (inDim === 1 && outDim > 1)) {\n result.unshift(outAxis);\n }\n }\n return result;\n}\n\nexport function assertAndGetBroadcastShape(\n shapeA: number[], shapeB: number[]): number[] {\n const l = Math.max(shapeA.length, shapeB.length);\n const result = new Array(l);\n\n for (let i = 0; i < l; i++) {\n let a = shapeA[shapeA.length - i - 1];\n if (a == null) {\n a = 1;\n }\n let b = shapeB[shapeB.length - i - 1];\n if (b == null) {\n b = 1;\n }\n if (a === 1) {\n result[l - i - 1] = b;\n } else if (b === 1) {\n result[l - i - 1] = a;\n } else if (a !== b) {\n const errMsg = `Operands could not be broadcast together with shapes ` +\n `${shapeA} and ${shapeB}.`;\n throw Error(errMsg);\n } else {\n result[l - i - 1] = a;\n }\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'maximum');\n let $b = convertToTensor(b, 'b', 'maximum');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'bool') {\n $a = cast($a, 'int32');\n $b = cast($b, 'int32');\n }\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: MaximumInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Maximum, inputs as unknown as NamedTensorMap);\n}\n\nexport const maximum = /* @__PURE__ */ op({maximum_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {abs} from '../ops/abs';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {maximum} from '../ops/maximum';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamaxOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Adamax';\n }\n private accBeta1: Variable;\n private iteration: Variable;\n\n private accumulatedFirstMoment: OptimizerVariable[] = [];\n private accumulatedWeightedInfNorm: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected beta1: number,\n protected beta2: number, protected epsilon: number = null,\n protected decay = 0.0) {\n super();\n\n tidy(() => {\n this.iteration = scalar(0).variable();\n this.accBeta1 = scalar(beta1).variable();\n });\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n }\n\n applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n tidy(() => {\n const oneMinusAccBeta1 = sub(1, this.accBeta1);\n const lr =\n div(-this.learningRate, add(mul(this.iteration, this.decay), 1));\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedFirstMoment[i] == null) {\n this.accumulatedFirstMoment[i] = {\n originalName: `${name}/m`,\n variable: zerosLike(value).variable(trainable)\n };\n }\n if (this.accumulatedWeightedInfNorm[i] == null) {\n this.accumulatedWeightedInfNorm[i] = {\n originalName: `${name}/v`,\n variable: zerosLike(value).variable(trainable)\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const firstMoment = this.accumulatedFirstMoment[i].variable;\n const weightedInfNorm = this.accumulatedWeightedInfNorm[i].variable;\n\n const newFirstMoment =\n add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n\n const ut0 = mul(weightedInfNorm, this.beta2);\n const ut1 = abs(gradient);\n\n const newWeightedInfNorm = maximum(ut0, ut1);\n\n firstMoment.assign(newFirstMoment);\n weightedInfNorm.assign(newWeightedInfNorm);\n\n const newValue =\n add(mul(div(lr, oneMinusAccBeta1),\n div(newFirstMoment, add(newWeightedInfNorm, this.epsilon))),\n value);\n\n value.assign(newValue);\n });\n\n this.iteration.assign(add(this.iteration, 1));\n this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.accBeta1.dispose();\n this.iteration.dispose();\n\n if (this.accumulatedFirstMoment != null) {\n dispose(this.accumulatedFirstMoment.map(v => v.variable));\n }\n if (this.accumulatedWeightedInfNorm != null) {\n dispose(this.accumulatedWeightedInfNorm.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise {\n throw new Error('getWeights() is not implemented for Adamax yet.');\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n throw new Error('setWeights() is not implemented for Adamax yet.');\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'beta1': this.beta1,\n 'beta2': this.beta2,\n 'epsilon': this.epsilon,\n 'decay': this.decay\n };\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['beta1'], config['beta2'],\n config['epsilon'], config['decay']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {keep, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer} from './optimizer';\n\n/** @doclink Optimizer */\nexport class SGDOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'SGD';\n }\n protected c: Scalar;\n\n constructor(protected learningRate: number) {\n super();\n this.setLearningRate(learningRate);\n }\n\n applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n const varNames = Array.isArray(variableGradients) ?\n variableGradients.map(v => v.name) :\n Object.keys(variableGradients);\n varNames.forEach((name, i) => {\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n const value = ENGINE.registeredVariables[name];\n tidy(() => {\n const newValue = add(mul(this.c, gradient), value);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n /**\n * Sets the learning rate of the optimizer.\n */\n setLearningRate(learningRate: number) {\n this.learningRate = learningRate;\n if (this.c != null) {\n this.c.dispose();\n }\n this.c = keep(scalar(-learningRate));\n }\n\n override dispose() {\n this.c.dispose();\n }\n\n override async getWeights(): Promise {\n return [await this.saveIterations()];\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n weightValues = await this.extractIterations(weightValues);\n if (weightValues.length !== 0) {\n throw new Error('SGD optimizer does not have settable weights.');\n }\n }\n\n getConfig(): ConfigDict {\n return {'learningRate': this.learningRate};\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(config['learningRate']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {OptimizerVariable} from './optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\n\n/** @doclink Optimizer */\nexport class MomentumOptimizer extends SGDOptimizer {\n /** @nocollapse */\n // Name matters for Python compatibility.\n static override get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'Momentum';\n }\n private m: Scalar;\n private accumulations: OptimizerVariable[] = [];\n\n constructor(\n protected override learningRate: number, private momentum: number,\n private useNesterov = false) {\n super(learningRate);\n this.m = scalar(this.momentum);\n }\n\n override applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n if (this.accumulations[i] == null) {\n const trainable = false;\n this.accumulations[i] = {\n originalName: `${name}/momentum`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const accumulation = this.accumulations[i].variable;\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n tidy(() => {\n let newValue: Tensor;\n const newAccumulation = add(mul(this.m, accumulation), gradient);\n if (this.useNesterov) {\n newValue = add(\n mul(this.c, add(gradient, mul(newAccumulation, this.m))), value);\n } else {\n newValue = add(mul(this.c, newAccumulation), value);\n }\n accumulation.assign(newAccumulation);\n value.assign(newValue);\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n this.m.dispose();\n if (this.accumulations != null) {\n dispose(this.accumulations.map(v => v.variable));\n }\n }\n\n /**\n * Sets the momentum of the optimizer.\n *\n * @param momentum\n */\n setMomentum(momentum: number) {\n this.momentum = momentum;\n }\n\n override async getWeights(): Promise {\n // Order matters for Python compatibility.\n return [await this.saveIterations()].concat(this.accumulations.map(\n v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n weightValues = await this.extractIterations(weightValues);\n const trainable = false;\n this.accumulations = weightValues.map(\n v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n }\n\n override getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'momentum': this.momentum,\n 'useNesterov': this.useNesterov\n };\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['momentum'], config['useNesterov']);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class RMSPropOptimizer extends Optimizer {\n /** @nocollapse */\n static get className() {\n // Name matters for Python compatibility.\n // This is a getter instead of a property because when it's a property, it\n // prevents the entire class from being tree-shaken.\n return 'RMSProp';\n }\n private centered: boolean;\n\n private accumulatedMeanSquares: OptimizerVariable[] = [];\n private accumulatedMoments: OptimizerVariable[] = [];\n private accumulatedMeanGrads: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, protected decay = 0.9,\n protected momentum = 0.0, protected epsilon: number = null,\n centered = false) {\n super();\n\n this.centered = centered;\n\n if (epsilon == null) {\n this.epsilon = ENGINE.backend.epsilon();\n }\n if (learningRate == null) {\n throw new Error(`learningRate for RMSPropOptimizer must be defined.`);\n }\n }\n\n applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n const variableNames = Array.isArray(variableGradients) ?\n variableGradients.map(item => item.name) :\n Object.keys(variableGradients);\n\n variableNames.forEach((name, i) => {\n const value = ENGINE.registeredVariables[name];\n const trainable = false;\n if (this.accumulatedMeanSquares[i] == null) {\n this.accumulatedMeanSquares[i] = {\n originalName: `${name}/rms`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedMoments[i] == null) {\n this.accumulatedMoments[i] = {\n originalName: `${name}/momentum`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n if (this.accumulatedMeanGrads[i] == null && this.centered) {\n this.accumulatedMeanGrads[i] = {\n originalName: `${name}/mg`,\n variable: tidy(() => zerosLike(value).variable(trainable))\n };\n }\n\n const gradient = Array.isArray(variableGradients) ?\n variableGradients[i].tensor :\n variableGradients[name];\n if (gradient == null) {\n return;\n }\n\n const accumulatedMeanSquare = this.accumulatedMeanSquares[i].variable;\n const accumulatedMoments = this.accumulatedMoments[i].variable;\n tidy(() => {\n const newAccumulatedMeanSquare =\n add(mul(accumulatedMeanSquare, this.decay),\n mul(square(gradient), 1 - this.decay));\n\n if (this.centered) {\n const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;\n // Centered gradient\n const newAccumulatedMeanGrad =\n add(mul(accumulatedMeanGrad, this.decay),\n mul(gradient, 1 - this.decay));\n\n const gradContribution =\n div(mul(gradient, this.learningRate),\n sqrt(\n sub(newAccumulatedMeanSquare,\n add(square(newAccumulatedMeanGrad), this.epsilon))));\n const newAccumulatedMoments =\n add(mul(accumulatedMoments, this.momentum), gradContribution);\n\n accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n accumulatedMeanGrad.assign(newAccumulatedMeanGrad);\n accumulatedMoments.assign(newAccumulatedMoments);\n\n const newValue = sub(value, newAccumulatedMoments);\n value.assign(newValue);\n } else {\n // Plain gradient\n const newAccumulatedMeanSquare =\n add(mul(accumulatedMeanSquare, this.decay),\n mul(square(gradient), 1 - this.decay));\n\n const newAccumulatedMoments =\n add(mul(accumulatedMoments, this.momentum),\n div(mul(gradient, this.learningRate),\n sqrt(add(newAccumulatedMeanSquare, this.epsilon))));\n\n accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n accumulatedMoments.assign(newAccumulatedMoments);\n\n const newValue = sub(value, newAccumulatedMoments);\n value.assign(newValue);\n }\n });\n });\n this.incrementIterations();\n }\n\n override dispose(): void {\n if (this.accumulatedMeanSquares != null) {\n dispose(this.accumulatedMeanSquares.map(v => v.variable));\n }\n if (this.accumulatedMeanGrads != null && this.centered) {\n dispose(this.accumulatedMeanGrads.map(v => v.variable));\n }\n if (this.accumulatedMoments != null) {\n dispose(this.accumulatedMoments.map(v => v.variable));\n }\n }\n\n override async getWeights(): Promise {\n // Order matters for Python compatibility.\n const variables: OptimizerVariable[] =\n [...this.accumulatedMeanSquares, ...this.accumulatedMoments];\n if (this.centered) {\n variables.push(...this.accumulatedMeanGrads);\n }\n return [await this.saveIterations()].concat(\n variables.map(v => ({name: v.originalName, tensor: v.variable})));\n }\n\n override async setWeights(weightValues: NamedTensor[]): Promise {\n weightValues = await this.extractIterations(weightValues);\n const variableCount =\n this.centered ? weightValues.length / 3 : weightValues.length / 2;\n const trainable = false;\n this.accumulatedMeanSquares =\n weightValues.slice(0, variableCount).map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(\n trainable)\n }));\n this.accumulatedMoments =\n weightValues.slice(variableCount, variableCount * 2)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n if (this.centered) {\n this.accumulatedMeanGrads =\n weightValues.slice(variableCount * 2, variableCount * 3)\n .map(v => ({\n originalName: v.name,\n variable: v.tensor.variable(trainable)\n }));\n }\n }\n\n getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'decay': this.decay,\n 'momentum': this.momentum,\n 'epsilon': this.epsilon,\n 'centered': this.centered\n };\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: SerializableConstructor, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['decay'], config['momentum'],\n config['epsilon'], config['centered']);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AdadeltaOptimizer} from './adadelta_optimizer';\nimport {AdagradOptimizer} from './adagrad_optimizer';\nimport {AdamOptimizer} from './adam_optimizer';\nimport {AdamaxOptimizer} from './adamax_optimizer';\nimport {MomentumOptimizer} from './momentum_optimizer';\nimport {RMSPropOptimizer} from './rmsprop_optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\nimport {registerClass} from '../serialization';\n\nconst OPTIMIZERS = [\n AdadeltaOptimizer,\n AdagradOptimizer,\n AdamOptimizer,\n AdamaxOptimizer,\n MomentumOptimizer,\n RMSPropOptimizer,\n SGDOptimizer,\n];\n\nexport function registerOptimizers() {\n for (const optimizer of OPTIMIZERS) {\n registerClass(optimizer);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers related to files, such as browser-triggered file downloads,\n * user-selected files in browser.\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {basename, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelJSON, SaveResult, WeightData, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\nconst DEFAULT_FILE_NAME_PREFIX = 'model';\nconst DEFAULT_JSON_EXTENSION_NAME = '.json';\nconst DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';\n\nfunction defer(f: () => T): Promise {\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 {\n if (typeof (document) === 'undefined') {\n throw new Error(\n 'Browser downloads are not supported in ' +\n 'this environment since `document` is not present');\n }\n\n // TODO(mattsoulanille): Support saving models over 2GB that exceed\n // Chrome's ArrayBuffer size limit.\n const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n const weightsURL = window.URL.createObjectURL(new Blob(\n [weightBuffer], {type: 'application/octet-stream'}));\n\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserDownloads.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./' + this.weightDataFileName],\n weights: modelArtifacts.weightSpecs\n }];\n const modelJSON: ModelJSON =\n getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n\n const modelJsonURL = window.URL.createObjectURL(\n new Blob([JSON.stringify(modelJSON)], {type: 'application/json'}));\n\n // If anchor elements are not provided, create them without attaching them\n // to parents, so that the downloaded file names can be controlled.\n const jsonAnchor = this.modelJsonAnchor == null ?\n document.createElement('a') :\n this.modelJsonAnchor;\n jsonAnchor.download = this.modelJsonFileName;\n jsonAnchor.href = modelJsonURL;\n // Trigger downloads by evoking a click event on the download anchors.\n // When multiple downloads are started synchronously, Firefox will only\n // save the last one.\n await defer(() => jsonAnchor.dispatchEvent(new MouseEvent('click')));\n\n if (modelArtifacts.weightData != null) {\n const weightDataAnchor = this.weightDataAnchor == null ?\n document.createElement('a') :\n this.weightDataAnchor;\n weightDataAnchor.download = this.weightDataFileName;\n weightDataAnchor.href = weightsURL;\n await defer(\n () => weightDataAnchor.dispatchEvent(new MouseEvent('click')));\n }\n\n return {modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts)};\n }\n }\n}\n\nclass BrowserFiles implements IOHandler {\n private readonly jsonFile: File;\n private readonly weightsFiles: File[];\n\n constructor(files: File[]) {\n if (files == null || files.length < 1) {\n throw new Error(\n `When calling browserFiles, at least 1 file is required, ` +\n `but received ${files}`);\n }\n this.jsonFile = files[0];\n this.weightsFiles = files.slice(1);\n }\n\n async load(): Promise {\n return new Promise((resolve, reject) => {\n const jsonReader = new FileReader();\n jsonReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;\n\n const modelTopology = modelJSON.modelTopology;\n if (modelTopology == null) {\n reject(new Error(`modelTopology field is missing from file ${\n this.jsonFile.name}`));\n return;\n }\n\n const weightsManifest = modelJSON.weightsManifest;\n if (weightsManifest == null) {\n reject(new Error(`weightManifest field is missing from file ${\n this.jsonFile.name}`));\n return;\n }\n\n if (this.weightsFiles.length === 0) {\n resolve({modelTopology});\n return;\n }\n\n const modelArtifactsPromise = getModelArtifactsForJSON(\n modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n resolve(modelArtifactsPromise);\n };\n\n jsonReader.onerror = error => reject(\n `Failed to read model topology and weights manifest JSON ` +\n `from file '${this.jsonFile.name}'. BrowserFiles supports loading ` +\n `Keras-style tf.Model artifacts only.`);\n jsonReader.readAsText(this.jsonFile);\n });\n }\n\n private loadWeights(weightsManifest: WeightsManifestConfig): Promise<[\n /* weightSpecs */ WeightsManifestEntry[], WeightData,\n ]> {\n const weightSpecs: WeightsManifestEntry[] = [];\n const paths: string[] = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n paths.push(...entry.paths);\n }\n\n const pathToFile: {[path: string]: File} =\n this.checkManifestAndWeightFiles(weightsManifest);\n\n const promises: Array> =\n paths.map(path => this.loadWeightsFile(path, pathToFile[path]));\n\n return Promise.all(promises).then(\n buffers => [weightSpecs, buffers]);\n }\n\n private loadWeightsFile(path: string, file: File): Promise {\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 (``)\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>, 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>): void {\n assert(\n promises != null && Array.isArray(promises) && promises.length > 0,\n () => 'promises must be a none empty array');\n }\n\n function checkFraction(startFraction: number, endFraction: number): void {\n assert(\n startFraction >= 0 && startFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got startFraction ${startFraction}`);\n assert(\n endFraction >= 0 && endFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got endFraction ${endFraction}`);\n assert(\n endFraction >= startFraction,\n () => `startFraction must be no more than endFraction, but ` +\n `got startFraction ${startFraction} and endFraction ` +\n `${endFraction}`);\n }\n\n return Promise.all(promises.map(registerMonitor));\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '../environment';\n\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {decodeWeights} from './io_utils';\nimport {monitorPromisesProgress} from './progress';\nimport {DTYPE_VALUE_SIZE_MAP, LoadOptions, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/**\n * Reads binary weights data from a number of URLs.\n *\n * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.\n * @param requestOptions RequestInit (options) for the HTTP requests.\n * @param fetchFunc Optional overriding value for the `window.fetch` function.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same\n * length as `fetchURLs`.\n */\nexport async function loadWeightsAsArrayBuffer(\n fetchURLs: string[], loadOptions?: LoadOptions): Promise {\n if (loadOptions == null) {\n loadOptions = {};\n }\n\n const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n loadOptions.fetchFunc;\n\n // Create the requests for all of the weights in parallel.\n const requests = fetchURLs.map(\n fetchURL =>\n fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true }));\n\n const fetchStartFraction = 0;\n const fetchEndFraction = 0.5;\n\n const responses = loadOptions.onProgress == null ?\n await Promise.all(requests) :\n await monitorPromisesProgress(\n requests, loadOptions.onProgress, fetchStartFraction,\n fetchEndFraction);\n\n const bufferPromises = responses.map(response => response.arrayBuffer());\n\n const bufferStartFraction = 0.5;\n const bufferEndFraction = 1;\n\n const buffers = loadOptions.onProgress == null ?\n await Promise.all(bufferPromises) :\n await monitorPromisesProgress(\n bufferPromises, loadOptions.onProgress, bufferStartFraction,\n bufferEndFraction);\n return buffers;\n}\n\nexport function streamWeights(fetchURLs: string[], loadOptions: LoadOptions): ReadableStream {\n const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n loadOptions.fetchFunc;\n\n let fetchIndex = 0;\n let chunkReader: ReadableStreamDefaultReader | undefined;\n loadOptions.onProgress?.(0);\n return new ReadableStream({\n pull: async (controller) => {\n while (fetchIndex < fetchURLs.length) {\n if (!chunkReader) {\n const body = (await fetchFunc(fetchURLs[fetchIndex],\n loadOptions.requestInit,\n {isBinary: true})).body;\n\n chunkReader = body.getReader();\n }\n\n const {done, value} = await chunkReader.read();\n\n if (done) {\n fetchIndex++;\n chunkReader = undefined;\n loadOptions.onProgress?.(fetchIndex / fetchURLs.length);\n continue;\n }\n controller.enqueue(value);\n return;\n }\n controller.close();\n },\n });\n}\n\n/**\n * Reads a weights manifest JSON configuration, fetches the weights and\n * returns them as `Tensor`s.\n *\n * @param manifest The weights manifest JSON.\n * @param filePathPrefix The path prefix for filenames given in the manifest.\n * Defaults to the empty string.\n * @param weightNames The names of the weights to be fetched.\n */\nexport async function loadWeights(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[],\n requestInit?: RequestInit): Promise {\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):\n (manifest: WeightsManifestConfig, filePathPrefix?: string,\n weightNames?: string[]) => Promise {\n return async (\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[]): Promise => {\n // Collect all the groups, weights, and their relative offsets to be\n // fetched.\n const groupIndicesToFetchMap = manifest.map(() => false);\n const groupWeightsToFetch: {\n [group: number]: Array<{\n manifestEntry: WeightsManifestEntry; groupOffset: number;\n sizeBytes: number;\n }>\n } = {};\n const weightsFound =\n weightNames != null ? weightNames.map(() => false) : [];\n const allManifestWeightNames: string[] = [];\n manifest.forEach((manifestGroupConfig, groupIndex) => {\n let groupOffset = 0;\n manifestGroupConfig.weights.forEach(weightsEntry => {\n const rawDtype = ('quantization' in weightsEntry) ?\n weightsEntry.quantization.dtype :\n weightsEntry.dtype;\n\n const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *\n util.sizeFromShape(weightsEntry.shape);\n\n const enqueueWeightsForFetchingFn = () => {\n groupIndicesToFetchMap[groupIndex] = true;\n if (groupWeightsToFetch[groupIndex] == null) {\n groupWeightsToFetch[groupIndex] = [];\n }\n\n groupWeightsToFetch[groupIndex].push({\n manifestEntry: weightsEntry,\n groupOffset,\n sizeBytes: weightsBytes\n });\n };\n\n if (weightNames != null) {\n weightNames.forEach((weightName, weightIndex) => {\n if (weightName === weightsEntry.name) {\n enqueueWeightsForFetchingFn();\n weightsFound[weightIndex] = true;\n }\n });\n } else {\n enqueueWeightsForFetchingFn();\n }\n\n allManifestWeightNames.push(weightsEntry.name);\n groupOffset += weightsBytes;\n });\n });\n\n if (!weightsFound.every(found => found)) {\n const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);\n throw new Error(\n `Could not find weights in manifest with names: ` +\n `${weightsNotFound.join(', ')}. \\n` +\n `Manifest JSON has weights with names: ` +\n `${allManifestWeightNames.join(', ')}.`);\n }\n\n // Convert the one-hot boolean groupId => shouldFetch map to a list of group\n // IDs.\n const groupIndicesToFetch =\n groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => {\n if (shouldFetch) {\n accumulator.push(i);\n }\n return accumulator;\n }, []);\n\n const fetchUrls: string[] = [];\n groupIndicesToFetch.forEach(i => {\n manifest[i].paths.forEach(filepath => {\n const fetchUrl = filePathPrefix +\n (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;\n fetchUrls.push(fetchUrl);\n });\n });\n const buffers = await fetchWeightsFunction(fetchUrls);\n\n const weightsTensorMap: NamedTensorMap = {};\n let bufferIndexOffset = 0;\n groupIndicesToFetch.forEach(i => {\n const numBuffers = manifest[i].paths.length;\n\n const weightsBuffer = new CompositeArrayBuffer(\n buffers.slice(bufferIndexOffset, bufferIndexOffset + numBuffers));\n\n const weightsEntries = groupWeightsToFetch[i];\n\n weightsEntries.forEach(weightsEntry => {\n const byteBuffer = weightsBuffer.slice(\n weightsEntry.groupOffset,\n weightsEntry.groupOffset + weightsEntry.sizeBytes);\n const nameToTensorMap =\n decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);\n for (const name in nameToTensorMap) {\n weightsTensorMap[name] = nameToTensorMap[name];\n }\n });\n\n bufferIndexOffset += numBuffers;\n });\n\n return weightsTensorMap;\n };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandler implementations based on HTTP requests in the web browser.\n *\n * Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n */\n\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts, getWeightSpecs} from './io_utils';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, LoadOptions, ModelArtifacts, ModelJSON, SaveResult, WeightData, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeightsAsArrayBuffer, streamWeights} from './weights_loader';\n\nconst OCTET_STREAM_MIME_TYPE = 'application/octet-stream';\nconst JSON_TYPE = 'application/json';\nexport class HTTPRequest implements IOHandler {\n protected readonly path: string;\n protected readonly requestInit: RequestInit;\n\n private readonly fetch: typeof fetch;\n private readonly weightUrlConverter: (weightName: string) => Promise;\n\n readonly DEFAULT_METHOD = 'POST';\n\n static readonly URL_SCHEME_REGEX = /^https?:\\/\\//;\n\n private readonly weightPathPrefix: string;\n private readonly loadOptions: LoadOptions;\n\n constructor(path: string, loadOptions?: LoadOptions) {\n if (loadOptions == null) {\n loadOptions = {};\n }\n this.weightPathPrefix = loadOptions.weightPathPrefix;\n this.weightUrlConverter = loadOptions.weightUrlConverter;\n\n if (loadOptions.fetchFunc != null) {\n assert(\n typeof loadOptions.fetchFunc === 'function',\n () => 'Must pass a function that matches the signature of ' +\n '`fetch` (see ' +\n 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)');\n this.fetch = loadOptions.fetchFunc;\n } else {\n this.fetch = env().platform.fetch;\n }\n\n assert(\n path != null && path.length > 0,\n () => 'URL path for http must not be null, undefined or ' +\n 'empty.');\n\n if (Array.isArray(path)) {\n assert(\n path.length === 2,\n () => 'URL paths for http must have a length of 2, ' +\n `(actual length is ${path.length}).`);\n }\n this.path = path;\n\n if (loadOptions.requestInit != null &&\n loadOptions.requestInit.body != null) {\n throw new Error(\n 'requestInit is expected to have no pre-existing body, but has one.');\n }\n this.requestInit = loadOptions.requestInit || {};\n this.loadOptions = loadOptions;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserHTTPRequest.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n const init = Object.assign({method: this.DEFAULT_METHOD}, this.requestInit);\n init.body = new FormData();\n\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./model.weights.bin'],\n weights: modelArtifacts.weightSpecs,\n }];\n const modelTopologyAndWeightManifest: ModelJSON =\n getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n\n init.body.append(\n 'model.json',\n new Blob(\n [JSON.stringify(modelTopologyAndWeightManifest)],\n {type: JSON_TYPE}),\n 'model.json');\n\n if (modelArtifacts.weightData != null) {\n // TODO(mattsoulanille): Support saving models over 2GB that exceed\n // Chrome's ArrayBuffer size limit.\n const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n init.body.append(\n 'model.weights.bin',\n new Blob([weightBuffer], {type: OCTET_STREAM_MIME_TYPE}),\n 'model.weights.bin');\n }\n\n const response = await this.fetch(this.path, init);\n\n if (response.ok) {\n return {\n modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),\n responses: [response],\n };\n } else {\n throw new Error(\n `BrowserHTTPRequest.save() failed due to HTTP response status ` +\n `${response.status}.`);\n }\n }\n\n private async loadModelJSON(): Promise {\n const modelConfigRequest = await this.fetch(this.path, this.requestInit);\n\n if (!modelConfigRequest.ok) {\n throw new Error(\n `Request to ${this.path} failed with status code ` +\n `${modelConfigRequest.status}. Please verify this URL points to ` +\n `the model JSON of the model to load.`);\n }\n let modelJSON: ModelJSON;\n try {\n modelJSON = await modelConfigRequest.json();\n } catch (e) {\n let message = `Failed to parse model JSON of response from ${this.path}.`;\n // TODO(nsthorat): Remove this after some time when we're comfortable that\n // .pb files are mostly gone.\n if (this.path.endsWith('.pb')) {\n message += ' Your path contains a .pb file extension. ' +\n 'Support for .pb models have been removed in TensorFlow.js 1.0 ' +\n 'in favor of .json models. You can re-convert your Python ' +\n 'TensorFlow model using the TensorFlow.js 1.0 conversion scripts ' +\n 'or you can convert your.pb models with the \\'pb2json\\'' +\n 'NPM script in the tensorflow/tfjs-converter repository.';\n } else {\n message += ' Please make sure the server is serving valid ' +\n 'JSON for this request.';\n }\n throw new Error(message);\n }\n\n // We do not allow both modelTopology and weightsManifest to be missing.\n const modelTopology = modelJSON.modelTopology;\n const weightsManifest = modelJSON.weightsManifest;\n if (modelTopology == null && weightsManifest == null) {\n throw new Error(\n `The JSON from HTTP path ${this.path} contains neither model ` +\n `topology or manifest for weights.`);\n }\n\n return modelJSON;\n }\n\n /**\n * Load model artifacts via HTTP request(s).\n *\n * See the documentation to `tf.io.http` for details on the saved\n * artifacts.\n *\n * @returns The loaded model artifacts (if loading succeeds).\n */\n async load(): Promise {\n if (this.loadOptions.streamWeights) {\n return this.loadStream();\n }\n const modelJSON = await this.loadModelJSON();\n return getModelArtifactsForJSON(\n modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n }\n\n private async loadStream(): Promise {\n const modelJSON = await this.loadModelJSON();\n const fetchURLs = await this.getWeightUrls(modelJSON.weightsManifest);\n const weightSpecs = getWeightSpecs(modelJSON.weightsManifest);\n const stream = () => streamWeights(fetchURLs, this.loadOptions);\n\n return {\n ...modelJSON,\n weightSpecs,\n getWeightStream: stream,\n };\n }\n\n private async getWeightUrls(weightsManifest: WeightsManifestConfig):\n Promise {\n const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;\n const [prefix, suffix] = parseUrl(weightPath);\n const pathPrefix = this.weightPathPrefix || prefix;\n\n const fetchURLs: string[] = [];\n const urlPromises: Array> = [];\n for (const weightsGroup of weightsManifest) {\n for (const path of weightsGroup.paths) {\n if (this.weightUrlConverter != null) {\n urlPromises.push(this.weightUrlConverter(path));\n } else {\n fetchURLs.push(pathPrefix + path + suffix);\n }\n }\n }\n\n if (this.weightUrlConverter) {\n fetchURLs.push(...await Promise.all(urlPromises));\n }\n return fetchURLs;\n }\n\n private async loadWeights(weightsManifest: WeightsManifestConfig):\n Promise<[WeightsManifestEntry[], WeightData]> {\n const fetchURLs = await this.getWeightUrls(weightsManifest);\n const weightSpecs = getWeightSpecs(weightsManifest);\n\n const buffers = await loadWeightsAsArrayBuffer(fetchURLs, this.loadOptions);\n return [weightSpecs, buffers];\n }\n}\n\n/**\n * Extract the prefix and suffix of the url, where the prefix is the path before\n * the last file, and suffix is the search params after the last file.\n * ```\n * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'\n * [prefix, suffix] = parseUrl(url)\n * // prefix = 'http://tfhub.dev/model/1/'\n * // suffix = '?tfjs-format=file'\n * ```\n * @param url the model url to be parsed.\n */\nexport function parseUrl(url: string): [string, string] {\n const lastSlash = url.lastIndexOf('/');\n const lastSearchParam = url.lastIndexOf('?');\n const prefix = url.substring(0, lastSlash);\n const suffix =\n lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';\n return [prefix + '/', suffix];\n}\n\nexport function isHTTPScheme(url: string): boolean {\n return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;\n}\n\nexport const httpRouter: IORouter =\n (url: string, loadOptions?: LoadOptions) => {\n if (typeof fetch === 'undefined' &&\n (loadOptions == null || loadOptions.fetchFunc == null)) {\n // `http` uses `fetch` or `node-fetch`, if one wants to use it in\n // an environment that is not the browser or node they have to setup a\n // global fetch polyfill.\n return null;\n } else {\n let isHTTP = true;\n if (Array.isArray(url)) {\n isHTTP = url.every(urlItem => isHTTPScheme(urlItem));\n } else {\n isHTTP = isHTTPScheme(url);\n }\n if (isHTTP) {\n return http(url, loadOptions);\n }\n }\n return null;\n };\nIORouterRegistry.registerSaveRouter(httpRouter);\nIORouterRegistry.registerLoadRouter(httpRouter);\n\n/**\n * Creates an IOHandler subtype that sends model artifacts to HTTP server.\n *\n * An HTTP request of the `multipart/form-data` mime type will be sent to the\n * `path` URL. The form data includes artifacts that represent the topology\n * and/or weights of the model. In the case of Keras-style `tf.Model`, two\n * blobs (files) exist in form-data:\n * - A JSON file consisting of `modelTopology` and `weightsManifest`.\n * - A binary weights file consisting of the concatenated weight values.\n * These files are in the same format as the one generated by\n * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).\n *\n * The following code snippet exemplifies the client-side code that uses this\n * function:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save(tf.io.http(\n * 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));\n * console.log(saveResult);\n * ```\n *\n * If the default `POST` method is to be used, without any custom parameters\n * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:\n *\n * ```js\n * const saveResult = await model.save('http://model-server:5000/upload');\n * ```\n *\n * The following GitHub Gist\n * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864\n * implements a server based on [flask](https://github.com/pallets/flask) that\n * can receive the request. Upon receiving the model artifacts via the requst,\n * this particular server reconstitutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n * Can be an absolute HTTP path (e.g.,\n * 'http://localhost:8000/model-upload)') or a relative path (e.g.,\n * './model-upload').\n * @param requestInit Request configurations to be used when sending\n * HTTP request to server using `fetch`. It can contain fields such as\n * `method`, `credentials`, `headers`, `mode`, etc. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n * for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n * following fields:\n * - weightPathPrefix Optional, this specifies the path prefix for weight\n * files, by default this is calculated from the path param.\n * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n * the `fetch` from node-fetch can be used here.\n * - onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function http(path: string, loadOptions?: LoadOptions): IOHandler {\n return new HTTPRequest(path, loadOptions);\n}\n\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nexport function browserHTTPRequest(\n path: string, loadOptions?: LoadOptions): IOHandler {\n return http(path, loadOptions);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers that pass through the in-memory ModelArtifacts format.\n */\n\nimport {IOHandler, IOHandlerSync, LoadHandler, ModelArtifacts, SaveHandler, SaveResult, TrainingConfig, WeightData, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandlerSync {\n constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n load(): ModelArtifacts {\n return this.modelArtifacts;\n }\n}\n\nclass PassthroughSaver> {\n constructor(\n private readonly saveHandler: (artifacts: ModelArtifacts) => R) {}\n\n save(modelArtifacts: ModelArtifacts): R {\n return this.saveHandler(modelArtifacts);\n }\n}\n\nclass PassthroughAsync implements IOHandler {\n load?: LoadHandler;\n save?: SaveHandler;\n\n constructor(handler: IOHandlerSync) {\n if (handler.load) {\n this.load = () => Promise.resolve(handler.load());\n }\n if (handler.save) {\n this.save = (modelArtifacts: ModelArtifacts) =>\n Promise.resolve(handler.save(modelArtifacts));\n }\n }\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data. Optional.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs. Optional.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: WeightData, trainingConfig?: TrainingConfig): IOHandler {\n\n const args = arguments as unknown as Parameters;\n return new PassthroughAsync(fromMemorySync(...args));\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data. Optional.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs. Optional.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandlerSync` that simply loads the provided data.\n */\nexport function fromMemorySync(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: WeightData, trainingConfig?: TrainingConfig): IOHandlerSync {\n if (arguments.length === 1) {\n const isModelArtifacts =\n (modelArtifacts as ModelArtifacts).modelTopology != null ||\n (modelArtifacts as ModelArtifacts).weightSpecs != null;\n if (isModelArtifacts) {\n return new PassthroughLoader(modelArtifacts as ModelArtifacts);\n } else {\n // Legacy support: with only modelTopology.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({modelTopology: modelArtifacts as {}});\n }\n } else {\n // Legacy support.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({\n modelTopology: modelArtifacts as {},\n weightSpecs,\n weightData,\n trainingConfig\n });\n }\n}\n\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * promise that resolves to a `SaveResult`.\n */\nexport function withSaveHandler(\n saveHandler: (artifacts: ModelArtifacts) =>\n Promise): IOHandler {\n return new PassthroughSaver(saveHandler);\n}\n\n/**\n * Creates an IOHandlerSync that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * `SaveResult`.\n */\nexport function withSaveHandlerSync(\n saveHandler: (artifacts: ModelArtifacts) => SaveResult): IOHandlerSync {\n return new PassthroughSaver(saveHandler);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike, transposeA = false,\n transposeB = false): T {\n let $a = convertToTensor(a, 'a', 'matMul');\n let $b = convertToTensor(b, 'b', 'matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: BatchMatMulInputs = {a: $a, b: $b};\n const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n return ENGINE.runKernel(\n BatchMatMul, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const matMul = /* @__PURE__ */ op({matMul_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n * `indices` used to encode prediction class must start from 0. For example,\n * if you have 3 classes of data, class 1 should be encoded as 0, class 2\n * should be 1, and class 3 should be 2.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`. Indices must\n * start from 0.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n * not match the location.\n * @param dtype The dtype of the output tensor, default to 'int32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n indices: Tensor|TensorLike, depth: number, onValue = 1, offValue = 0,\n dtype: DataType = 'int32'): Tensor {\n if (depth < 2) {\n throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n }\n const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n\n const inputs: OneHotInputs = {indices: $indices};\n const attrs: OneHotAttrs = {dtype, depth, onValue, offValue};\n\n return ENGINE.runKernel(\n OneHot, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = /* @__PURE__ */ op({oneHot_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(input: T|TensorLike): T {\n const $input = convertToTensor(input, 'input', 'imag');\n\n const inputs: ImagInputs = {input: $input};\n return ENGINE.runKernel(Imag, inputs as unknown as NamedTensorMap);\n}\n\nexport const imag = /* @__PURE__ */ op({imag_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'neg');\n\n const inputs: NegInputs = {x: $x};\n return ENGINE.runKernel(Neg, inputs as unknown as NamedTensorMap);\n}\nexport const neg = /* @__PURE__ */ op({neg_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(input: T|TensorLike): T {\n const $input = convertToTensor(input, 'input', 'real');\n\n const inputs: RealInputs = {input: $input};\n return ENGINE.runKernel(Real, inputs as unknown as NamedTensorMap);\n}\n\nexport const real = /* @__PURE__ */ op({real_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {tidy} from '../globals';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {complex} from './complex';\nimport {imag} from './imag';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {real} from './real';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print(); // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n * @param conjugate Will conjugate complex input if true.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_(\n x: T|TensorLike, perm?: number[], conjugate?: boolean): T {\n const $x = convertToTensor(x, 'x', 'transpose');\n\n if (perm == null) {\n perm = $x.shape.map((s, i) => i).reverse();\n }\n util.assert(\n $x.rank === perm.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of perm ${perm}.`);\n perm.forEach(axis => {\n util.assert(\n axis >= 0 && axis < $x.rank,\n () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n ` but got ${perm}`);\n });\n\n if ($x.rank <= 1) {\n return $x.clone();\n }\n\n const inputs: TransposeInputs = {x: $x};\n const attrs: TransposeAttrs = {perm};\n\n if ($x.dtype === 'complex64') {\n return tidy(() => {\n let $real = real($x);\n let $imag = imag($x);\n $real = ENGINE.runKernel(\n Transpose, {x: $real} as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n $imag = ENGINE.runKernel(\n Transpose, {x: $imag} as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n if (conjugate) {\n $imag = neg($imag);\n }\n return complex($real, $imag);\n });\n }\n\n return ENGINE.runKernel(\n Transpose, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const transpose = /* @__PURE__ */ op({transpose_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {matMul} from './mat_mul';\nimport {oneHot} from './one_hot';\nimport {op} from './operation';\nimport {transpose} from './transpose';\n\n/**\n * Computes the confusion matrix from true labels and predicted labels.\n *\n * ```js\n * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');\n * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');\n * const numClasses = 3;\n * const out = tf.math.confusionMatrix(labels, predictions, numClasses);\n * out.print();\n * // Expected output matrix:\n * // [[2, 0, 0],\n * // [0, 1, 1],\n * // [0, 0, 1]]\n * ```\n *\n * @param labels The target labels, assumed to be 0-based integers\n * for the classes. The shape is `[numExamples]`, where\n * `numExamples` is the number of examples included.\n * @param predictions The predicted classes, assumed to be\n * 0-based integers for the classes. Must have the same shape as `labels`.\n * @param numClasses Number of all classes, as an integer.\n * Its value must be larger than the largest element in `labels` and\n * `predictions`.\n * @returns The confusion matrix as a int32-type 2D tensor. The value at\n * row `r` and column `c` is the number of times examples of actual class\n * `r` were predicted as class `c`.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function confusionMatrix_(\n labels: Tensor1D|TensorLike, predictions: Tensor1D|TensorLike,\n numClasses: number): Tensor2D {\n const $labels = convertToTensor(labels, 'labels', 'confusionMatrix');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'confusionMatrix');\n\n util.assert(\n numClasses == null || numClasses > 0 && Number.isInteger(numClasses),\n () => `If provided, numClasses must be a positive integer, ` +\n `but got ${numClasses}`);\n util.assert(\n $labels.rank === 1,\n () => `Expected the rank of labels to be 1, but got ${$labels.rank}`);\n util.assert(\n $predictions.rank === 1,\n () => `Expected the rank of predictions to be 1, ` +\n `but got ${$predictions.rank}`);\n util.assert(\n $labels.shape[0] === $predictions.shape[0],\n () => `Mismatch in the number of examples: ` +\n `${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +\n `Labels and predictions should have the same number of elements.`);\n util.assert(\n numClasses > 0 && Number.isInteger(numClasses),\n () => `numClasses is required to be a positive integer, but got ` +\n `${numClasses}`);\n // TODO(cais): In the future, if oneHot supports tensors inputs for\n // `numClasses`, `confusionMatrix` can make `numClasses` optional.\n\n const oneHotLabels = oneHot(cast($labels, 'int32'), numClasses) as Tensor2D;\n const oneHotPredictions =\n oneHot(cast($predictions, 'int32'), numClasses) as Tensor2D;\n const oneHotLabelsT: Tensor2D = transpose(oneHotLabels);\n const product: Tensor2D = matMul(oneHotLabelsT, oneHotPredictions);\n return cast(product, 'int32');\n}\n\nexport const confusionMatrix = /* @__PURE__ */ op({confusionMatrix_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\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 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {env} from '../environment';\nimport {Draw, DrawAttrs, DrawInputs, FromPixels, FromPixelsAttrs, FromPixelsInputs} from '../kernel_names';\nimport {getKernel, NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor2D, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DrawOptions, ImageOptions, PixelData, TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\nimport {tensor3d} from './tensor3d';\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\nlet hasToPixelsWarned = false;\n\n/**\n * Creates a `tf.Tensor` from an image.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * tf.browser.fromPixels(image).print();\n * ```\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @returns A Tensor3D with the shape `[height, width, numChannels]`.\n *\n * Note: fromPixels can be lossy in some cases, same image may result in\n * slightly different tensor values, if rendered by different rendering\n * engines. This means that results from different browsers, or even same\n * browser with CPU and GPU rendering engines can be different. See discussion\n * in details:\n * https://github.com/tensorflow/tfjs/issues/5482\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nfunction fromPixels_(\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap,\n numChannels = 3): Tensor3D {\n // Sanity checks.\n if (numChannels > 4) {\n throw new Error(\n 'Cannot construct Tensor with more than 4 channels from pixels.');\n }\n if (pixels == null) {\n throw new Error('pixels passed to tf.browser.fromPixels() can not be null');\n }\n let isPixelData = false;\n let isImageData = false;\n let isVideo = false;\n let isImage = false;\n let isCanvasLike = false;\n let isImageBitmap = false;\n if ((pixels as PixelData).data instanceof Uint8Array) {\n isPixelData = true;\n } else if (\n typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {\n isImageData = true;\n } else if (\n typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement) {\n isVideo = true;\n } else if (\n typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement) {\n isImage = true;\n // tslint:disable-next-line: no-any\n } else if ((pixels as any).getContext != null) {\n isCanvasLike = true;\n } else if (\n typeof (ImageBitmap) !== 'undefined' && pixels instanceof ImageBitmap) {\n isImageBitmap = true;\n } else {\n throw new Error(\n 'pixels passed to tf.browser.fromPixels() must be either an ' +\n `HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +\n `in browser, or OffscreenCanvas, ImageData in webworker` +\n ` or {data: Uint32Array, width: number, height: number}, ` +\n `but was ${(pixels as {}).constructor.name}`);\n }\n // If the current backend has 'FromPixels' registered, it has a more\n // efficient way of handling pixel uploads, so we call that.\n const kernel = getKernel(FromPixels, ENGINE.backendName);\n if (kernel != null) {\n const inputs: FromPixelsInputs = {pixels};\n const attrs: FromPixelsAttrs = {numChannels};\n return ENGINE.runKernel(\n FromPixels, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n }\n\n const [width, height] = isVideo ?\n [\n (pixels as HTMLVideoElement).videoWidth,\n (pixels as HTMLVideoElement).videoHeight\n ] :\n [pixels.width, pixels.height];\n let vals: Uint8ClampedArray|Uint8Array;\n\n if (isCanvasLike) {\n vals =\n // tslint:disable-next-line:no-any\n (pixels as any).getContext('2d').getImageData(0, 0, width, height).data;\n } else if (isImageData || isPixelData) {\n vals = (pixels as PixelData | ImageData).data;\n } else if (isImage || isVideo || isImageBitmap) {\n if (fromPixels2DContext == null) {\n if (typeof document === 'undefined') {\n if (typeof OffscreenCanvas !== 'undefined' &&\n typeof OffscreenCanvasRenderingContext2D !== 'undefined') {\n // @ts-ignore\n fromPixels2DContext = new OffscreenCanvas(1, 1).getContext('2d');\n } else {\n throw new Error(\n 'Cannot parse input in current context. ' +\n 'Reason: OffscreenCanvas Context2D rendering is not supported.');\n }\n } else {\n fromPixels2DContext = document.createElement('canvas').getContext(\n '2d', {willReadFrequently: true});\n }\n }\n fromPixels2DContext.canvas.width = width;\n fromPixels2DContext.canvas.height = height;\n fromPixels2DContext.drawImage(\n pixels as HTMLVideoElement, 0, 0, width, height);\n vals = fromPixels2DContext.getImageData(0, 0, width, height).data;\n }\n let values: Int32Array;\n if (numChannels === 4) {\n values = new Int32Array(vals);\n } else {\n const numPixels = width * height;\n values = new Int32Array(numPixels * numChannels);\n for (let i = 0; i < numPixels; i++) {\n for (let channel = 0; channel < numChannels; ++channel) {\n values[i * numChannels + channel] = vals[i * 4 + channel];\n }\n }\n }\n const outShape: [number, number, number] = [height, width, numChannels];\n return tensor3d(values, outShape, 'int32');\n}\n\n// Helper functions for |fromPixelsAsync| to check whether the input can\n// be wrapped into imageBitmap.\nfunction isPixelData(pixels: PixelData|ImageData|HTMLImageElement|\n HTMLCanvasElement|HTMLVideoElement|\n ImageBitmap): pixels is PixelData {\n return (pixels != null) && ((pixels as PixelData).data instanceof Uint8Array);\n}\n\nfunction isImageBitmapFullySupported() {\n return typeof window !== 'undefined' &&\n typeof (ImageBitmap) !== 'undefined' &&\n window.hasOwnProperty('createImageBitmap');\n}\n\nfunction isNonEmptyPixels(pixels: PixelData|ImageData|HTMLImageElement|\n HTMLCanvasElement|HTMLVideoElement|ImageBitmap) {\n return pixels != null && pixels.width !== 0 && pixels.height !== 0;\n}\n\nfunction canWrapPixelsToImageBitmap(pixels: PixelData|ImageData|\n HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap) {\n return isImageBitmapFullySupported() && !(pixels instanceof ImageBitmap) &&\n isNonEmptyPixels(pixels) && !isPixelData(pixels);\n}\n\n/**\n * Creates a `tf.Tensor` from an image in async way.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * (await tf.browser.fromPixelsAsync(image)).print();\n * ```\n * This API is the async version of fromPixels. The API will first\n * check |WRAP_TO_IMAGEBITMAP| flag, and try to wrap the input to\n * imageBitmap if the flag is set to true.\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nexport async function fromPixelsAsync(\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap,\n numChannels = 3) {\n let inputs: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap = null;\n\n // Check whether the backend needs to wrap |pixels| to imageBitmap and\n // whether |pixels| can be wrapped to imageBitmap.\n if (env().getBool('WRAP_TO_IMAGEBITMAP') &&\n canWrapPixelsToImageBitmap(pixels)) {\n // Force the imageBitmap creation to not do any premultiply alpha\n // ops.\n let imageBitmap;\n\n try {\n // wrap in try-catch block, because createImageBitmap may not work\n // properly in some browsers, e.g.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1335594\n // tslint:disable-next-line: no-any\n imageBitmap = await (createImageBitmap as any)(\n pixels as ImageBitmapSource, {premultiplyAlpha: 'none'});\n } catch (e) {\n imageBitmap = null;\n }\n\n // createImageBitmap will clip the source size.\n // In some cases, the input will have larger size than its content.\n // E.g. new Image(10, 10) but with 1 x 1 content. Using\n // createImageBitmap will clip the size from 10 x 10 to 1 x 1, which\n // is not correct. We should avoid wrapping such resouce to\n // imageBitmap.\n if (imageBitmap != null && imageBitmap.width === pixels.width &&\n imageBitmap.height === pixels.height) {\n inputs = imageBitmap;\n } else {\n inputs = pixels;\n }\n } else {\n inputs = pixels;\n }\n\n return fromPixels_(inputs, numChannels);\n}\n\nfunction validateImgTensor(img: Tensor2D|Tensor3D) {\n if (img.rank !== 2 && img.rank !== 3) {\n throw new Error(\n `toPixels only supports rank 2 or 3 tensors, got rank ${img.rank}.`);\n }\n const depth = img.rank === 2 ? 1 : img.shape[2];\n\n if (depth > 4 || depth === 2) {\n throw new Error(\n `toPixels only supports depth of size ` +\n `1, 3 or 4 but got ${depth}`);\n }\n\n if (img.dtype !== 'float32' && img.dtype !== 'int32') {\n throw new Error(\n `Unsupported type for toPixels: ${img.dtype}.` +\n ` Please use float32 or int32 tensors.`);\n }\n}\n\nfunction validateImageOptions(imageOptions: ImageOptions) {\n const alpha = imageOptions ?.alpha || 1;\n if (alpha > 1 || alpha < 0) {\n throw new Error(`Alpha value ${alpha} is suppoed to be in range [0 - 1].`);\n }\n}\n\n/**\n * Draws a `tf.Tensor` of pixel values to a byte array or optionally a\n * canvas.\n *\n * When the dtype of the input is 'float32', we assume values in the range\n * [0-1]. Otherwise, when input is 'int32', we assume values in the range\n * [0-255].\n *\n * Returns a promise that resolves when the canvas has been drawn to.\n *\n * @param img A rank-2 tensor with shape `[height, width]`, or a rank-3 tensor\n * of shape `[height, width, numChannels]`. If rank-2, draws grayscale. If\n * rank-3, must have depth of 1, 3 or 4. When depth of 1, draws\n * grayscale. When depth of 3, we draw with the first three components of\n * the depth dimension corresponding to r, g, b and alpha = 1. When depth of\n * 4, all four components of the depth dimension correspond to r, g, b, a.\n * @param canvas The canvas to draw to.\n *\n * @doc {heading: 'Browser', namespace: 'browser'}\n */\nexport async function toPixels(\n img: Tensor2D|Tensor3D|TensorLike,\n canvas?: HTMLCanvasElement): Promise {\n let $img = convertToTensor(img, 'img', 'toPixels');\n if (!(img instanceof Tensor)) {\n // Assume int32 if user passed a native array.\n const originalImgTensor = $img;\n $img = cast(originalImgTensor, 'int32');\n originalImgTensor.dispose();\n }\n validateImgTensor($img);\n\n const [height, width] = $img.shape.slice(0, 2);\n const depth = $img.rank === 2 ? 1 : $img.shape[2];\n const data = await $img.data();\n const multiplier = $img.dtype === 'float32' ? 255 : 1;\n const bytes = new Uint8ClampedArray(width * height * 4);\n\n for (let i = 0; i < height * width; ++i) {\n const rgba = [0, 0, 0, 255];\n\n for (let d = 0; d < depth; d++) {\n const value = data[i * depth + d];\n\n if ($img.dtype === 'float32') {\n if (value < 0 || value > 1) {\n throw new Error(\n `Tensor values for a float32 Tensor must be in the ` +\n `range [0 - 1] but encountered ${value}.`);\n }\n } else if ($img.dtype === 'int32') {\n if (value < 0 || value > 255) {\n throw new Error(\n `Tensor values for a int32 Tensor must be in the ` +\n `range [0 - 255] but encountered ${value}.`);\n }\n }\n\n if (depth === 1) {\n rgba[0] = value * multiplier;\n rgba[1] = value * multiplier;\n rgba[2] = value * multiplier;\n } else {\n rgba[d] = value * multiplier;\n }\n }\n\n const j = i * 4;\n bytes[j + 0] = Math.round(rgba[0]);\n bytes[j + 1] = Math.round(rgba[1]);\n bytes[j + 2] = Math.round(rgba[2]);\n bytes[j + 3] = Math.round(rgba[3]);\n }\n\n if (canvas != null) {\n if (!hasToPixelsWarned) {\n const kernel = getKernel(Draw, ENGINE.backendName);\n if (kernel != null) {\n console.warn(\n 'tf.browser.toPixels is not efficient to draw tensor on canvas. ' +\n 'Please try tf.browser.draw instead.');\n hasToPixelsWarned = true;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d');\n const imageData = new ImageData(bytes, width, height);\n ctx.putImageData(imageData, 0, 0);\n }\n if ($img !== img) {\n $img.dispose();\n }\n return bytes;\n}\n\n/**\n * Draws a `tf.Tensor` to a canvas.\n *\n * When the dtype of the input is 'float32', we assume values in the range\n * [0-1]. Otherwise, when input is 'int32', we assume values in the range\n * [0-255].\n *\n * @param image The tensor to draw on the canvas. Must match one of\n * these shapes:\n * - Rank-2 with shape `[height, width`]: Drawn as grayscale.\n * - Rank-3 with shape `[height, width, 1]`: Drawn as grayscale.\n * - Rank-3 with shape `[height, width, 3]`: Drawn as RGB with alpha set in\n * `imageOptions` (defaults to 1, which is opaque).\n * - Rank-3 with shape `[height, width, 4]`: Drawn as RGBA.\n * @param canvas The canvas to draw to.\n * @param options The configuration arguments for image to be drawn and the\n * canvas to draw to.\n *\n * @doc {heading: 'Browser', namespace: 'browser'}\n */\nexport function draw(\n image: Tensor2D|Tensor3D|TensorLike, canvas: HTMLCanvasElement,\n options?: DrawOptions): void {\n let $img = convertToTensor(image, 'img', 'draw');\n if (!(image instanceof Tensor)) {\n // Assume int32 if user passed a native array.\n const originalImgTensor = $img;\n $img = cast(originalImgTensor, 'int32');\n originalImgTensor.dispose();\n }\n validateImgTensor($img);\n validateImageOptions(options?.imageOptions);\n\n const inputs: DrawInputs = {image: $img};\n const attrs: DrawAttrs = {canvas, options};\n ENGINE.runKernel(\n Draw, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const fromPixels = /* @__PURE__ */ op({fromPixels_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorInfo } from '../tensor_info';\nimport {computeStrides, sizeFromShape} from '../util';\n\n/**\n * Validate gather nd inputs.\n *\n * @param tensor The tensor contains the source values.\n * @param indices The tensor contains the indices to slice the source.\n *\n * @returns [resultShape, numUpdates, sliceSize, strides]\n */\nexport function prepareAndValidate(tensor: TensorInfo, indices: TensorInfo):\n [number[], number, number, number[]] {\n const tensorRank = tensor.shape.length;\n const indicesRank = indices.shape.length;\n if (tensorRank < 1) {\n throw new Error(\n 'tf.gatherND() expects the input to be rank 1 or higher,' +\n ` but the rank was ${tensorRank}.`);\n }\n if (indicesRank < 1) {\n throw new Error(\n 'tf.gatherND() expects the indices to be rank 1 or higher,' +\n ` but the rank was ${indicesRank}.`);\n }\n if (indices.dtype !== 'int32') {\n throw new Error(\n 'tf.gatherND() expects the indices to be int32 type,' +\n ` but the dtype was ${indices.dtype}.`);\n }\n if (indices.shape[indicesRank - 1] > tensorRank) {\n throw new Error(\n 'index innermost dimension length must be <= tensor rank; saw: ' +\n `${indices.shape[indicesRank - 1]} vs. ${tensorRank}`);\n }\n\n if (sizeFromShape(tensor.shape) === 0) {\n throw new Error(\n 'Requested more than 0 entries, but input is empty.' +\n ` Input shape: ${tensor.shape}.`);\n }\n\n const indicesShape = indices.shape;\n const sliceRank = indicesShape[indicesShape.length - 1];\n\n // The result shape is\n // indices.shape[:-1] + params.shape[indices.shape[-1]:]\n let nResult = 1;\n for (let i = 0; i < indicesShape.length - 1; ++i) {\n nResult *= indicesShape[i];\n }\n\n const inputShape = tensor.shape;\n\n const resultShape = indicesShape.slice();\n resultShape.pop();\n\n let sliceSize = 1;\n for (let i = sliceRank; i < tensorRank; ++i) {\n sliceSize *= inputShape[i];\n resultShape.push(inputShape[i]);\n }\n\n const strides =\n [...computeStrides(tensor.shape).map(stride => stride / sliceSize),\n 1].slice(0, sliceRank);\n\n return [resultShape, nResult, sliceSize, strides];\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorInfo } from '../tensor_info';\nimport {Tensor} from '../tensor';\nimport {computeStrides, sizeFromShape} from '../util';\n\n/**\n * Check whether updates.shape = indices.shape[:batchDim] +\n * shape[sliceDim:]\n *\n * @param x The input tensor.\n */\nexport function validateUpdateShape(\n shape: number[], indices: Tensor, updates: Tensor) {\n const sliceDim = (indices.rank > 1) ? indices.shape[indices.rank - 1] : 1;\n const batchDim = (indices.rank > 1) ? indices.rank - 1 : 1;\n\n const shapeError = 'Must have updates.shape = indices.shape[:batchDim] + ' +\n `shape[sliceDim:], got updates.shape: ${updates.shape}` +\n `, indices.shape: ${indices.shape}, shape: ${shape}` +\n `, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;\n\n if (updates.rank < batchDim) {\n throw new Error(shapeError + ` update.rank < ${batchDim}. `);\n }\n if (shape.length < sliceDim + (updates.rank - batchDim)) {\n throw new Error(\n shapeError +\n ` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);\n }\n if (updates.rank !== batchDim + shape.length - sliceDim) {\n throw new Error(\n shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);\n }\n for (let d = 0; d < batchDim; ++d) {\n if (updates.shape[d] !== indices.shape[d]) {\n throw new Error(\n shapeError +\n ` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${\n indices.shape[d]}).`);\n }\n }\n for (let d = 0; d < updates.rank - batchDim; ++d) {\n if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {\n throw new Error(\n shapeError +\n ` updates.shape[${d + batchDim}] (${\n updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${\n shape[d + batchDim]})`);\n }\n }\n}\n\nexport interface ScatterShapeInfo {\n sliceRank: number;\n numUpdates: number;\n sliceSize: number;\n strides: number[];\n outputSize: number;\n}\n/**\n * Validate scatter nd inputs.\n *\n * @param update The tensor contains the update values.\n * @param indices The tensor contains the indices for the update values.\n * @param shape The shape of the output tensor.\n */\nexport function validateInput(\n updates: Tensor, indices: Tensor, shape: number[]) {\n if (indices.rank < 1) {\n throw new Error(\n 'tf.scatterND() expects the indices to be rank 1 or higher,' +\n ` but the rank was ${indices.rank}.`);\n }\n if (updates.rank < 1) {\n throw new Error(\n 'tf.scatterND() expects the updates to be rank 1 or higher,' +\n ` but the rank was ${updates.rank}.`);\n }\n if (indices.dtype !== 'int32') {\n throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${\n indices.dtype}`);\n }\n if (shape.length < 1) {\n throw new Error(\n `Output rank must be greater or equal to 1, but got shape: ${shape}`);\n }\n\n if (shape.length === 0) {\n if (indices.size === 0) {\n throw new Error(`Indices specified for empty output. indices shape: ${\n indices.shape}`);\n }\n if (updates.size === 0) {\n throw new Error(`Updates specified for empty output. updates shape: ${\n updates.shape}`);\n }\n }\n\n validateUpdateShape(shape, indices, updates);\n}\n\n/**\n * Calculate the shape information for the output.\n *\n * @param update The tensor contains the update values.\n * @param indices The tensor contains the indices for the update values.\n * @param shape The shape of the output tensor.\n *\n * @returns ScatterShapeInfo\n */\nexport function calculateShapes(\n updates: TensorInfo, indices: TensorInfo,\n shape: number[]): ScatterShapeInfo {\n // Calculate the number of dimensions in indices\n const indicesRank = indices.shape.length;\n const sliceRank = (indicesRank > 1) ? indices.shape[indicesRank - 1] : 1;\n\n // Calculate the number of elements that make up each slice of our updated\n // tensor. This allows us to work with flattened tensors and copy over whole\n // slices at a time.\n const totalNd = shape.length;\n\n let sliceSize = 1;\n for (let i = sliceRank; i < totalNd; ++i) {\n sliceSize *= shape[i];\n }\n\n const safeSliceDim = (sliceRank < 1) ? 1 : sliceRank;\n const numUpdates = sizeFromShape(indices.shape) / safeSliceDim;\n\n const strides = [...computeStrides(shape.slice(0, sliceRank)), 1];\n const outputSize = sizeFromShape(shape);\n return {sliceRank, numUpdates, sliceSize, strides, outputSize};\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { TensorInfo } from '../tensor_info';\nimport * as util from '../util';\n\nconst NEW_AXIS = -2;\nconst SHRINK_AXIS = -1;\n\n// Sparse slicing specification\n// if one does foo[3:5, ..., -3], the begin, end and strides will have length\n// of 3.\ninterface StridedSliceSparseSpec {\n dims: number;\n numAddAxisAfterEllipsis: number;\n begin: number[];\n end: number[];\n strides: number[];\n beginMask: number;\n endMask: number;\n ellipsisMask: number;\n newAxisMask: number;\n shrinkAxisMask: number;\n}\n\n// Dense slicing specification\n// all ellipses and newaxis are expanded out. So if foo[3:5, ..., -3] where foo\n// is 10 dimensional, each array of begin, end, strides will have 10 entries\n// where as the sparse can have length less than the rank of foo.\ninterface StridedSliceDenseSpec {\n dims: number;\n beginMask?: number;\n endMask?: number;\n beginValid: boolean;\n endValid: boolean;\n begin?: number[];\n end?: number[];\n strides?: number[];\n // This array helps construct the final shape of the slice.\n // The final tensor is reduced in rank whenever a single index e.g. foo[3]\n // is called for. The final tensor increases in rank with newAxis entries.\n // If an index in this array is positive, the size of the dimension is\n // obtained from canonical end-begin. Otherwise, if it is a NEW_AXIS, it will\n // be 1. A shrunk dimension is skipped.\n finalShapeGatherIndices?: number[];\n // This array has the same size as finalShapeGatherIndices, but it remembers\n // the sparse index that a dimension comes from, instead of dense index.\n // A -1 in this vector means the index is not from the sparse input.\n finalShapeGatherIndicesSparse?: number[];\n inputShapeGatherIndicesSparse?: number[];\n // The dense indexed shrink mask is which processing dimensions should be\n // shrunk. For example, if foo.shape = [10, 10, 10, 10], foo[3, ..., 5] has\n // sparseShrinkAxisMask of 5 (0101) and denseShrinkAxisMask of 9 (1001),\n // yielding a final shape [10, 10].\n shrinkAxisMask?: number;\n}\n\nexport type SliceInfo = {\n finalShapeSparse: number[],\n finalShape: number[],\n isIdentity: boolean,\n sliceDim0: boolean,\n isSimpleSlice: boolean,\n begin: number[],\n end: number[],\n strides: number[]\n};\n\nexport function assertParamsValid(\n input: TensorInfo, begin: number[], size: number[]): void {\n const inputRank = input.shape.length;\n util.assert(\n inputRank === begin.length,\n () => `Error in slice${inputRank}D: Length of begin ${begin} must ` +\n `match the rank of the array (${inputRank}).`);\n util.assert(\n inputRank === size.length,\n () => `Error in slice${inputRank}D: Length of size ${size} must ` +\n `match the rank of the array (${inputRank}).`);\n\n for (let i = 0; i < inputRank; ++i) {\n util.assert(\n begin[i] + size[i] <= input.shape[i],\n () => `Error in slice${inputRank}D: begin[${i}] + size[${i}] ` +\n `(${begin[i] + size[i]}) would overflow input.shape[${i}] (${\n input.shape[i]})`);\n }\n}\n\n/** Converts a binary mask to an array of axes. Used in stridedSlice(). */\nexport function maskToAxes(mask: number): number[] {\n const axes = [];\n let axis = 0;\n while (mask > 0) {\n if (mask & 1) {\n axes.push(axis);\n }\n mask /= 2;\n axis++;\n }\n return axes;\n}\n\n/** Computes the output shape given the strided slice params. */\nexport function computeOutShape(\n begin: number[], end: number[], strides: number[]): number[] {\n const size = [];\n for (let axis = 0; axis < begin.length; axis++) {\n size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);\n }\n return size;\n}\n\n// Creates full selection at the elided dimensions. If the dimension matches\n// the ellipsis mask, override the current stride value. Otherwise, insert.\nexport function stridesWithElidedDims(\n strides: number[], ellipsisInsertionIndex: number, numElidedAxes: number,\n inputShape: number[]): number[] {\n const newStrides = [...strides];\n for (let i = newStrides.length; i < inputShape.length; i++) {\n newStrides.push(1);\n }\n for (let i = 0; i < numElidedAxes; i++) {\n if (i === 0) {\n newStrides[ellipsisInsertionIndex] = 1;\n } else {\n newStrides.splice(\n ellipsisInsertionIndex, 0 /* num elements to delete */,\n 1 /* element to add */);\n newStrides.pop();\n }\n }\n return newStrides;\n}\n\nfunction unnormalizeAxis(\n ellipsisInsertionIndex: number, numElidedAxes: number,\n normalizedAxis: number): number {\n if (normalizedAxis <= ellipsisInsertionIndex) {\n return normalizedAxis;\n }\n\n return normalizedAxis - (numElidedAxes - 1);\n}\n\nfunction getElidedAxes(numElidedAxes: number, ellipsisInsertionIndex: number) {\n const elidedAxes = [];\n for (let i = 0; i < numElidedAxes; i++) {\n elidedAxes.push(ellipsisInsertionIndex + i);\n }\n return elidedAxes;\n}\n\n// Normalize the start, end and strides.\nexport function getNormalizedAxes(\n inputShape: number[], ellipsisAxes: number[], numInterpolatedAxes: number,\n begin: number[], end: number[], strides: number[], beginMask: number,\n endMask: number,\n ellipsisMask: number): {begin: number[], end: number[], strides: number[]} {\n const inputRank = inputShape.length;\n let normalizedBegin = new Array(inputRank),\n normalizedEnd = new Array(inputRank),\n normalizedStrides = new Array(inputRank);\n if (ellipsisAxes.length && numInterpolatedAxes > 0) {\n const fullIndex = ellipsisAxes[0];\n\n // The ellipsis applies to the masked index as well as any dimensions\n // that are interpolated.\n const numElidedAxes = numInterpolatedAxes + 1;\n normalizedBegin = startIndicesWithElidedDims(\n beginMask, fullIndex, numElidedAxes, begin, inputShape);\n normalizedEnd = stopIndicesWithElidedDims(\n endMask, fullIndex, numElidedAxes, end, inputShape);\n normalizedStrides =\n stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);\n } else {\n for (let axis = 0; axis < inputRank; axis++) {\n normalizedBegin[axis] = startForAxis(\n beginMask, begin, strides, inputShape, axis, ellipsisMask);\n normalizedEnd[axis] =\n stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);\n normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);\n }\n }\n\n return {\n begin: normalizedBegin,\n end: normalizedEnd,\n strides: normalizedStrides\n };\n}\n\n// Creates full selection at the elided dimensions. If the dimension matches\n// the ellipsis mask, override the current start value. Otherwise, insert.\nexport function startIndicesWithElidedDims(\n beginMask: number, ellipsisInsertionIndex: number, numElidedAxes: number,\n originalBegin: number[], inputShape: number[]): number[] {\n const newIndices = [...inputShape];\n const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);\n\n for (let axis = 0; axis < newIndices.length; axis++) {\n if (elidedAxes.indexOf(axis) > -1) {\n newIndices[axis] = 0;\n } else {\n const originalAxis =\n unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);\n let originalValue = originalBegin[originalAxis];\n if (beginMask & 1 << originalAxis) {\n originalValue = 0;\n }\n\n newIndices[axis] = originalValue;\n }\n }\n return newIndices;\n}\n\n// Creates full selection at the elided dimensions. If the dimension matches\n// the ellipsis mask, override the current stop value. Otherwise, insert.\nexport function stopIndicesWithElidedDims(\n endMask: number, ellipsisInsertionIndex: number, numElidedAxes: number,\n originalEnd: number[], inputShape: number[]): number[] {\n const newIndices = [...inputShape];\n const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);\n\n for (let axis = 0; axis < newIndices.length; axis++) {\n if (elidedAxes.indexOf(axis) > -1) {\n newIndices[axis] = Number.MAX_SAFE_INTEGER;\n } else {\n const originalAxis =\n unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);\n let originalValue = originalEnd[originalAxis];\n if (endMask & 1 << originalAxis) {\n originalValue = Number.MAX_SAFE_INTEGER;\n }\n newIndices[axis] = originalValue;\n }\n }\n\n for (let i = 0; i < newIndices.length; i++) {\n // Handle negative indices\n const axisSize = inputShape[i];\n if (newIndices[i] < 0) {\n newIndices[i] += axisSize;\n }\n newIndices[i] = util.clamp(0, newIndices[i], inputShape[i]);\n }\n return newIndices;\n}\n\nexport function stridesForAxis(\n strides: number[], axis: number, ellipsisMask: number): number {\n let stride = strides[axis];\n if (ellipsisMask & (1 << axis) || stride == null) {\n stride = 1;\n }\n\n return stride;\n}\n\nexport function startForAxis(\n beginMask: number, startIndices: number[], strides: number[],\n inputShape: number[], axis: number, ellipsisMask: number): number {\n // Begin with the specified index\n let start = startIndices[axis];\n const stride = strides[axis] || 1;\n\n // Check the axis bit from right of masked axes, or the begin index is not set\n // for the axis.\n if (beginMask & 1 << axis || ellipsisMask & 1 << axis || start == null) {\n if (stride > 0) {\n // Forward iteration - use the first element. These values will get\n // clamped below (Note: We could have set them to 0 and axis_size-1, but\n // use lowest() and max() to maintain symmetry with StopForAxis())\n start = Number.MIN_SAFE_INTEGER;\n } else {\n // Backward iteration - use the last element.\n start = Number.MAX_SAFE_INTEGER;\n }\n }\n\n // Handle negative indices\n const axisSize = inputShape[axis];\n if (start < 0) {\n start += axisSize;\n }\n\n // Clamping\n start = util.clamp(0, start, axisSize - 1);\n\n return start;\n}\n\nexport function stopForAxis(\n endMask: number, stopIndices: number[], strides: number[],\n inputShape: number[], axis: number, ellipsisMask: number): number {\n // Begin with the specified index\n let stop = stopIndices[axis];\n const stride = strides[axis] || 1;\n\n // Check the axis bit from right of masked axes, or if the stop index is not\n // set for this axis.\n if (endMask & (1 << axis) || ellipsisMask & (1 << axis) || stop == null) {\n if (stride > 0) {\n // Forward iteration - use the last element. These values will get\n // clamped below\n stop = Number.MAX_SAFE_INTEGER;\n } else {\n // Backward iteration - use the first element.\n stop = Number.MIN_SAFE_INTEGER;\n }\n }\n\n // Handle negative indices\n const axisSize = inputShape[axis];\n if (stop < 0) {\n stop += axisSize;\n }\n\n // Clamping\n // Because the end index points one past the last element, we need slightly\n // different clamping ranges depending on the direction.\n if (stride > 0) {\n // Forward iteration\n stop = util.clamp(0, stop, axisSize);\n } else {\n // Backward iteration\n stop = util.clamp(-1, stop, axisSize - 1);\n }\n\n return stop;\n}\n\n/**\n * Returns true if the slice occupies a continous set of elements in the\n * 'flat' space.\n */\nexport function isSliceContinous(\n shape: number[], begin: number[], size: number[]) {\n // Index of the first axis that has size > 1.\n let firstNonOneAxis = size.length;\n for (let i = 0; i < size.length; i++) {\n if (size[i] > 1) {\n firstNonOneAxis = i;\n break;\n }\n }\n\n for (let i = firstNonOneAxis + 1; i < size.length; i++) {\n if (begin[i] > 0 || size[i] !== shape[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function computeFlatOffset(begin: number[], strides: number[]): number {\n let flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;\n for (let i = 0; i < begin.length - 1; i++) {\n flatOffset += begin[i] * strides[i];\n }\n return flatOffset;\n}\n\nexport function parseSliceParams(\n x: TensorInfo, begin: number|number[], size?: number|number[]) {\n // The following logic allows for more ergonomic calls.\n let begin_: number[];\n const xRank = x.shape.length;\n if (typeof begin === 'number') {\n begin_ = [begin, ...new Array(xRank - 1).fill(0)];\n } else if (begin.length < xRank) {\n begin_ = begin.concat(new Array(xRank - begin.length).fill(0));\n } else {\n begin_ = begin.slice();\n }\n begin_.forEach(d => {\n util.assert(\n d !== -1, () => 'slice() does not support negative begin indexing.');\n });\n let size_: number[];\n if (size == null) {\n size_ = new Array(xRank).fill(-1);\n } else if (typeof size === 'number') {\n size_ = [size, ...new Array(xRank - 1).fill(-1)];\n } else if (size.length < xRank) {\n size_ = size.concat(new Array(xRank - size.length).fill(-1));\n } else {\n size_ = size;\n }\n size_ = size_.map((d, i) => {\n if (d >= 0) {\n return d;\n } else {\n util.assert(\n d === -1,\n () => `Negative size values should be exactly -1 but got ` +\n `${d} for the slice() size at index ${i}.`);\n return x.shape[i] - begin_[i];\n }\n });\n return [begin_, size_];\n}\n\n// Convert the slicing specification from a sparse representation to a dense\n// representation. This means that all ellipses and newaxis are expanded out.\nexport function sliceInfo(\n xShape: number[], begin: number[], end: number[], strides: number[],\n beginMask: number, endMask: number, ellipsisMask: number,\n newAxisMask: number, shrinkAxisMask: number): SliceInfo {\n let stridesNonNull;\n if (strides == null) {\n stridesNonNull = new Array(begin.length);\n stridesNonNull.fill(1);\n } else {\n stridesNonNull = strides;\n }\n\n // Only one non-zero bit is allowed in ellipsisMask, which means ellipsisMask\n // is a power of 2. Use bit compares to ensure ellipsisMask is 0 or a power\n // of 2. When i is a power of 2, i & (i - 1) is always 0.\n // Also ref:\n // https://stackoverflow.com/questions/600293/how-to-check-if-a-number-is-a-power-of-2\n if (ellipsisMask != null && (ellipsisMask & (ellipsisMask - 1)) !== 0) {\n throw new Error('Multiple ellipses in slice is not allowed.');\n }\n\n // Step 1: Account for ellipsis and new axis.\n // Check for ellipsis and count how many non-newaxis there are after.\n let ellipsisSeen = false;\n\n const sparseSpec: StridedSliceSparseSpec = {\n dims: stridesNonNull.length,\n numAddAxisAfterEllipsis: 0,\n begin: begin.slice(),\n end: end.slice(),\n strides: stridesNonNull.slice(),\n beginMask,\n endMask,\n ellipsisMask,\n newAxisMask,\n shrinkAxisMask\n };\n\n for (let i = 0; i < sparseSpec.dims; i++) {\n if (ellipsisSeen && ((1 << i) & newAxisMask) !== 0) {\n sparseSpec.numAddAxisAfterEllipsis++;\n }\n if ((1 << i) & ellipsisMask) {\n ellipsisSeen = true;\n }\n }\n // If no ellipsis insert one at the end.\n if (!ellipsisSeen) {\n sparseSpec.ellipsisMask |= (1 << sparseSpec.dims);\n sparseSpec.dims++; // this effects loop iteration below\n }\n\n // Step 2: Make a sparse spec into a full index spec.\n //\n // The sparse spec deos not correspond to the number of dimensions.\n // Make a dense spec that cooresponds to the number of dimensions.\n //\n // For example suppose foo[...,3:] on foo.shape = [2, 2, 3] then we need to\n // produce the missing beginMask for the first two dimensions i.e. from\n // beginMaskSpec = 0, endMaskSpec = 2, we achieve beginMask = 6 (110),\n // endMask = 7 (111).\n const denseSpec: StridedSliceDenseSpec = {\n dims: xShape.length,\n beginMask: 0,\n endMask: 0,\n beginValid: false,\n endValid: false\n };\n\n buildDenseSpec(sparseSpec, denseSpec);\n\n // Step 3: Make implicit ranges (non-zero beginMasks and endMasks) explicit\n // and bounds check.\n let isIdentity = true;\n let sliceDim0 = true;\n let isSimpleSlice = true;\n const processingShape = [];\n const finalShape = [];\n\n for (let i = 0; i < xShape.length; ++i) {\n if (denseSpec.strides[i] === 0) {\n throw Error(`strides[${i}] must be non-zero`);\n }\n const shrinkI = !!(denseSpec.shrinkAxisMask & (1 << i));\n const dimI = xShape[i];\n if (dimI === -1) {\n processingShape.push(shrinkI ? 1 : -1);\n continue;\n }\n\n const masks =\n [denseSpec.beginMask & (1 << i), denseSpec.endMask & (1 << i)];\n const validRange = [\n denseSpec.strides[i] > 0 ? 0 : -1,\n denseSpec.strides[i] > 0 ? dimI : dimI - 1\n ];\n\n if (shrinkI && denseSpec.strides[i] <= 0) {\n throw Error('only stride 1 allowed on non-range indexing.');\n }\n\n isSimpleSlice = isSimpleSlice && (denseSpec.strides[i] === 1);\n\n const beginAndEndMasked =\n !!((denseSpec.beginMask & (1 << i)) && (denseSpec.endMask & (1 << i)));\n\n if (denseSpec.beginValid && denseSpec.endValid) {\n if (shrinkI) {\n // If we are shrinking, the end index is now possibly incorrect. In\n // particular foo[-1] produces sparseBegin = -1, sparseEnd = 0.\n // and canonical puts these to n-1 and 0, which implies a degenerate\n // interval. Fortunately, it is now safe to re-create end as begin + 1.\n const xFwd = denseSpec.begin[i] < 0 ? dimI + denseSpec.begin[i] :\n denseSpec.begin[i];\n denseSpec.begin[i] = xFwd;\n denseSpec.end[i] = denseSpec.begin[i] + 1;\n if (xFwd < 0 || xFwd >= dimI) {\n throw Error(`slice index ${denseSpec.begin[i]} of dimension ${\n i} out of bounds.`);\n }\n } else {\n denseSpec.begin[i] = canonical(\n denseSpec.begin[i], 0, denseSpec.strides[i], dimI, masks,\n validRange);\n denseSpec.end[i] = canonical(\n denseSpec.end[i], 1, denseSpec.strides[i], dimI, masks, validRange);\n }\n // Update optimization values\n const takeAllInDimension = denseSpec.strides[i] === 1 &&\n denseSpec.begin[i] === 0 && denseSpec.end[i] === dimI;\n isIdentity = isIdentity && takeAllInDimension;\n sliceDim0 = sliceDim0 &&\n ((i === 0 && denseSpec.strides[i] === 1) || takeAllInDimension);\n } else {\n isIdentity =\n isIdentity && ((denseSpec.strides[i] === 1) && beginAndEndMasked);\n sliceDim0 = sliceDim0 &&\n ((i === 0 && denseSpec.strides[i] === 1) || beginAndEndMasked);\n }\n // Compute the processing shape (the intermediate Eigen will produce)\n let intervalLength;\n let knownInterval = false;\n if (denseSpec.beginValid && denseSpec.endValid) {\n intervalLength = denseSpec.end[i] - denseSpec.begin[i];\n knownInterval = true;\n } else if (shrinkI) {\n // The dimension is still known as 1 for the processingShape, but will be\n // discarded for the final shape.\n intervalLength = 1;\n knownInterval = true;\n } else if (beginAndEndMasked) {\n // Even if we don't have values for begin or end, we do know that this\n // dimension covers the whole interval. If we have shape information for\n // this dimension, that tells us the interval length.\n if (dimI >= 0) {\n if (denseSpec.strides[i] < 0) {\n intervalLength = -dimI;\n } else {\n intervalLength = dimI;\n }\n knownInterval = true;\n }\n }\n if (knownInterval) {\n let sizeI;\n // Hold zero if the interval is degenerate, otherwise account for\n // remainder\n if (intervalLength === 0 ||\n ((intervalLength < 0) !== (denseSpec.strides[i] < 0))) {\n sizeI = 0;\n } else {\n sizeI = Math.trunc(intervalLength / denseSpec.strides[i]) +\n (intervalLength % denseSpec.strides[i] !== 0 ? 1 : 0);\n }\n processingShape.push(sizeI);\n } else {\n processingShape.push(-1);\n }\n }\n\n // Step 4: Compute the final shape\n //\n // newAxis will increase dimension by 1 (with a one-size dimension)\n // slices like foo[3, ...] will reduce dimension by 1.\n // This cannot be done earlier, because it depends on Step 3.\n for (let denseDim = 0; denseDim < denseSpec.finalShapeGatherIndices.length;\n ++denseDim) {\n const gatherIndex = denseSpec.finalShapeGatherIndices[denseDim];\n if (gatherIndex >= 0) {\n finalShape.push(processingShape[gatherIndex]);\n } else if (gatherIndex === NEW_AXIS) {\n finalShape.push(1);\n }\n }\n\n const finalShapeSparse = finalShape.filter(\n (dim, i) => denseSpec.finalShapeGatherIndices[i] !== NEW_AXIS);\n\n return {\n finalShapeSparse,\n finalShape,\n isIdentity,\n sliceDim0,\n isSimpleSlice,\n begin: denseSpec.begin,\n end: denseSpec.end,\n strides: denseSpec.strides\n };\n}\n\nfunction buildDenseSpec(\n sparse: StridedSliceSparseSpec, dense: StridedSliceDenseSpec) {\n dense.beginMask = 0;\n dense.endMask = 0;\n dense.shrinkAxisMask = 0;\n\n let fullIndex = 0;\n dense.beginValid = sparse.begin != null;\n dense.endValid = sparse.end != null;\n\n dense.begin = new Array(dense.dims);\n dense.end = new Array(dense.dims);\n dense.strides = new Array(dense.dims);\n dense.finalShapeGatherIndices = [];\n dense.finalShapeGatherIndicesSparse = [];\n dense.inputShapeGatherIndicesSparse = new Array(dense.dims);\n\n for (let i = 0; i < sparse.dims; i++) {\n if ((1 << i) & sparse.ellipsisMask) {\n // Only the bit that has ellipsis will fall in this condition.\n // Expand the ellipsis into the appropriate indices\n // Note: this only works because we guaranteed one ellipsis.\n const nextIndex = Math.min(\n dense.dims - (sparse.dims - i) + 1 + sparse.numAddAxisAfterEllipsis,\n dense.dims);\n for (; fullIndex < nextIndex; fullIndex++) {\n // newAxis aren't real axis so you have to skip.\n dense.begin[fullIndex] = 0;\n dense.end[fullIndex] = 0;\n dense.strides[fullIndex] = 1;\n dense.beginMask |= (1 << fullIndex);\n dense.endMask |= (1 << fullIndex);\n dense.finalShapeGatherIndices.push(fullIndex);\n dense.finalShapeGatherIndicesSparse.push(-1);\n dense.inputShapeGatherIndicesSparse[fullIndex] = i;\n }\n } else if ((1 << i) & sparse.newAxisMask) {\n // Only the bit that has newAxis will fall in this condition.\n dense.finalShapeGatherIndices.push(NEW_AXIS);\n dense.finalShapeGatherIndicesSparse.push(-1);\n } else {\n if (fullIndex === dense.begin.length) {\n throw Error(\n `Index out of range using input dim ${fullIndex}; input ` +\n `has only ${dense.dims} dims, ${dense.begin.length}.`);\n }\n\n // Gather slicing spec into appropriate index.\n if (sparse.begin != null) {\n dense.begin[fullIndex] = sparse.begin[i];\n }\n if (sparse.end != null) {\n dense.end[fullIndex] = sparse.end[i];\n }\n dense.strides[fullIndex] = sparse.strides[i];\n if (sparse.beginMask & (1 << i)) {\n dense.beginMask |= (1 << fullIndex);\n }\n if (sparse.endMask & (1 << i)) {\n dense.endMask |= (1 << fullIndex);\n }\n // If shrink, record where to get the dimensionality from (i.e. newAxis)\n // creates a fake 1 size dimension. Also remember shrink axis (now in\n // dense form) so we can ignore dense.end below.\n if (sparse.shrinkAxisMask & (1 << i)) {\n dense.finalShapeGatherIndices.push(SHRINK_AXIS);\n dense.finalShapeGatherIndicesSparse.push(-1);\n dense.shrinkAxisMask |= (1 << fullIndex);\n } else {\n dense.finalShapeGatherIndices.push(fullIndex);\n // Remember that where in the sparse shape the dense dim comes from.\n dense.finalShapeGatherIndicesSparse.push(i);\n }\n dense.inputShapeGatherIndicesSparse[fullIndex] = i;\n fullIndex++;\n }\n }\n}\n\nfunction canonical(\n x: number, c: number, strideI: number, dimI: number, masks: number[],\n validRange: number[]) {\n if (masks[c]) {\n return strideI > 0 ? validRange[c] : validRange[(c + 1) & 1];\n } else {\n const xFwd = x < 0 ? dimI + x : x; // make negative indices positive\n return xFwd < validRange[0] ? validRange[0] :\n xFwd > validRange[1] ? validRange[1] : xFwd;\n }\n}\n","/**\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,\n expected: TypedArray|number|RecursiveArray, 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);\n const expectedFlat = isTypedArray(expected) ?\n expected :\n flatten(expected as RecursiveArray);\n\n if (actualFlat.length !== expectedFlat.length) {\n throw new Error(\n `Arrays have different lengths actual: ${actualFlat.length} vs ` +\n `expected: ${expectedFlat.length}.\\n` +\n `Actual: ${actualFlat}.\\n` +\n `Expected: ${expectedFlat}.`);\n }\n for (let i = 0; i < expectedFlat.length; ++i) {\n const a = actualFlat[i];\n const e = expectedFlat[i];\n\n if (!predicate(a, e)) {\n throw new Error(\n `Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.\\n` +\n `Actual: ${actualFlat}.\\n` +\n `Expected: ${expectedFlat}.`);\n }\n }\n if (typeof expect !== 'undefined') {\n expect().nothing();\n }\n}\n\nexport interface DoneFn {\n (): void;\n fail: (message?: Error|string) => void;\n}\n\nexport function expectPromiseToFail(fn: () => Promise<{}>, done: DoneFn): void {\n fn().then(() => done.fail(), () => done());\n if (typeof expect !== 'undefined') {\n expect().nothing();\n }\n}\n\nexport function expectArraysEqual(actual: TensorLike, expected: TensorLike) {\n const exp = typeof expected === 'string' || typeof expected === 'number' ||\n typeof expected === 'boolean' ?\n [expected] as number[] :\n expected as number[];\n if (isString(actual) || isString((actual as string[])[0]) ||\n isString(expected) || isString((expected as string[])[0])) {\n // tslint:disable-next-line: triple-equals\n return expectArraysPredicate(actual, exp, (a, b) => a == b);\n }\n return expectArraysPredicate(\n actual, expected, (a, b) => areClose(a as number, b as number, 0));\n}\n\nexport function expectNumbersClose(a: number, e: number, epsilon?: number) {\n if (epsilon == null) {\n epsilon = testEpsilon();\n }\n if (!areClose(a, e, epsilon)) {\n throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`);\n }\n if (typeof expect !== 'undefined') {\n expect().nothing();\n }\n}\n\nfunction areClose(a: number, e: number, epsilon: number): boolean {\n if (!isFinite(a) && !isFinite(e)) {\n return true;\n }\n if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {\n return false;\n }\n return true;\n}\n\nexport function expectValuesInRange(\n actual: TypedArray|number[], low: number, high: number) {\n for (let i = 0; i < actual.length; i++) {\n if (actual[i] < low || actual[i] > high) {\n throw new Error(\n `Value out of range:${actual[i]} low: ${low}, high: ${high}`);\n }\n }\n}\n\nexport function expectArrayBuffersEqual(\n actual: ArrayBuffer, expected: ArrayBuffer) {\n // Safari does not like comparing ArrayBuffers directly. Wrapping in\n // a Float32Array solves this issue.\n const actualArray = new Float32Array(actual);\n const expectedArray = new Float32Array(expected);\n if (actualArray.length !== expectedArray.length) {\n throw new Error(\n 'Expected ArrayBuffer to be of length ' +\n `${expectedArray.length}, but it was ${actualArray.length}`);\n }\n\n for (let i = 0; i < expectedArray.length; i++) {\n if (actualArray[i] !== expectedArray[i]) {\n throw new Error(\n `Expected ArrayBuffer value at ${i} to be ` +\n `${expectedArray[i]} but got ${actualArray[i]} instead`);\n }\n }\n}\n\n/** Encodes strings into utf-8 bytes. */\nexport function encodeStrings(a: RecursiveArray<{}>):\n RecursiveArray {\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;\n}\n\n/** Creates an HTMLVideoElement with autoplay-friendly default settings. */\nexport function createVideoElement(source: HTMLSourceElement):\n Promise {\n const video = document.createElement('video');\n if ('playsInline' in video) {\n // tslint:disable-next-line:no-any\n (video as any).playsInline = true;\n }\n video.muted = true;\n video.loop = true;\n video.style.position = 'fixed';\n video.style.left = '0px';\n video.style.top = '0px';\n\n video.preload = 'auto';\n video.appendChild(source);\n return new Promise(resolve => {\n video.addEventListener('loadeddata', _ => resolve(video));\n video.load();\n });\n}\n\nexport async function play(video: HTMLVideoElement) {\n await video.play();\n if ('requestVideoFrameCallback' in video) {\n await new Promise(resolve => {\n // tslint:disable-next-line:no-any\n (video as any).requestVideoFrameCallback(resolve);\n });\n }\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.0';\nexport {version};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AdadeltaOptimizer} from './adadelta_optimizer';\nimport {AdagradOptimizer} from './adagrad_optimizer';\nimport {AdamOptimizer} from './adam_optimizer';\nimport {AdamaxOptimizer} from './adamax_optimizer';\nimport {MomentumOptimizer} from './momentum_optimizer';\nimport {RMSPropOptimizer} from './rmsprop_optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\n\nexport class OptimizerConstructors {\n /**\n * Constructs a `tf.SGDOptimizer` that uses stochastic gradient descent.\n *\n * ```js\n * // Fit a quadratic function by learning the coefficients a, b, c.\n * const xs = tf.tensor1d([0, 1, 2, 3]);\n * const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);\n *\n * const a = tf.scalar(Math.random()).variable();\n * const b = tf.scalar(Math.random()).variable();\n * const c = tf.scalar(Math.random()).variable();\n *\n * // y = a * x^2 + b * x + c.\n * const f = x => a.mul(x.square()).add(b.mul(x)).add(c);\n * const loss = (pred, label) => pred.sub(label).square().mean();\n *\n * const learningRate = 0.01;\n * const optimizer = tf.train.sgd(learningRate);\n *\n * // Train the model.\n * for (let i = 0; i < 10; i++) {\n * optimizer.minimize(() => loss(f(xs), ys));\n * }\n *\n * // Make predictions.\n * console.log(\n * `a: ${a.dataSync()}, b: ${b.dataSync()}, c: ${c.dataSync()}`);\n * const preds = f(xs).dataSync();\n * preds.forEach((pred, i) => {\n * console.log(`x: ${i}, pred: ${pred}`);\n * });\n * ```\n *\n * @param learningRate The learning rate to use for the SGD algorithm.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static sgd(learningRate: number): SGDOptimizer {\n return new SGDOptimizer(learningRate);\n }\n\n /**\n * Constructs a `tf.MomentumOptimizer` that uses momentum gradient\n * descent.\n *\n * See\n * [http://proceedings.mlr.press/v28/sutskever13.pdf](\n * http://proceedings.mlr.press/v28/sutskever13.pdf)\n *\n * @param learningRate The learning rate to use for the Momentum gradient\n * descent algorithm.\n * @param momentum The momentum to use for the momentum gradient descent\n * algorithm.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static momentum(learningRate: number, momentum: number, useNesterov = false):\n MomentumOptimizer {\n return new MomentumOptimizer(learningRate, momentum, useNesterov);\n }\n\n /**\n * Constructs a `tf.RMSPropOptimizer` that uses RMSProp gradient\n * descent. This implementation uses plain momentum and is not centered\n * version of RMSProp.\n *\n * See\n * [http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf](\n * http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n *\n * @param learningRate The learning rate to use for the RMSProp gradient\n * descent algorithm.\n * @param decay The discounting factor for the history/coming gradient.\n * @param momentum The momentum to use for the RMSProp gradient descent\n * algorithm.\n * @param epsilon Small value to avoid zero denominator.\n * @param centered If true, gradients are normalized by the estimated\n * variance of the gradient.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static rmsprop(\n learningRate: number, decay = .9, momentum = 0.0, epsilon: number = null,\n centered = false): RMSPropOptimizer {\n return new RMSPropOptimizer(\n learningRate, decay, momentum, epsilon, centered);\n }\n\n /**\n * Constructs a `tf.AdamOptimizer` that uses the Adam algorithm.\n * See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)\n *\n * @param learningRate The learning rate to use for the Adam gradient\n * descent algorithm.\n * @param beta1 The exponential decay rate for the 1st moment estimates.\n * @param beta2 The exponential decay rate for the 2nd moment estimates.\n * @param epsilon A small constant for numerical stability.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static adam(\n learningRate = 0.001, beta1 = 0.9, beta2 = 0.999,\n epsilon: number = null): AdamOptimizer {\n return new AdamOptimizer(learningRate, beta1, beta2, epsilon);\n }\n\n /**\n * Constructs a `tf.AdadeltaOptimizer` that uses the Adadelta algorithm.\n * See [https://arxiv.org/abs/1212.5701](https://arxiv.org/abs/1212.5701)\n *\n * @param learningRate The learning rate to use for the Adadelta gradient\n * descent algorithm.\n * @param rho The learning rate decay over each update.\n * @param epsilon A constant epsilon used to better condition the grad\n * update.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static adadelta(learningRate = .001, rho = .95, epsilon: number = null):\n AdadeltaOptimizer {\n return new AdadeltaOptimizer(learningRate, rho, epsilon);\n }\n\n /**\n * Constructs a `tf.AdamaxOptimizer` that uses the Adamax algorithm.\n * See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)\n *\n * @param learningRate The learning rate to use for the Adamax gradient\n * descent algorithm.\n * @param beta1 The exponential decay rate for the 1st moment estimates.\n * @param beta2 The exponential decay rate for the 2nd moment estimates.\n * @param epsilon A small constant for numerical stability.\n * @param decay The learning rate decay over each update.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static adamax(\n learningRate = 0.002, beta1 = 0.9, beta2 = 0.999, epsilon: number = null,\n decay = 0.0): AdamaxOptimizer {\n return new AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay);\n }\n\n /**\n * Constructs a `tf.AdagradOptimizer` that uses the Adagrad algorithm.\n * See\n * [http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf](\n * http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)\n * or\n * [http://ruder.io/optimizing-gradient-descent/index.html#adagrad](\n * http://ruder.io/optimizing-gradient-descent/index.html#adagrad)\n *\n * @param learningRate The learning rate to use for the Adagrad gradient\n * descent algorithm.\n * @param initialAccumulatorValue Starting value for the accumulators, must be\n * positive.\n *\n * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n */\n static adagrad(learningRate: number, initialAccumulatorValue = 0.1):\n AdagradOptimizer {\n return new AdagradOptimizer(learningRate, initialAccumulatorValue);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'acos');\n const inputs: AcosInputs = {x: $x};\n\n return ENGINE.runKernel(Acos, inputs as unknown as NamedTensorMap);\n}\nexport const acos = /* @__PURE__ */ op({acos_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Acosh, AcoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:\n * `acosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([10, 1, 3, 5.7]);\n *\n * x.acosh().print(); // or tf.acosh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction acosh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'acosh');\n const inputs: AcoshInputs = {x: $x};\n\n return ENGINE.runKernel(Acosh, inputs as unknown as NamedTensorMap);\n}\nexport const acosh = /* @__PURE__ */ op({acosh_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {AddN, AddNInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n *\n * tf.addN([a, b, c]).print();\n * ```\n * @param tensors A list of tensors with the same shape and dtype.\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction addN_(tensors: Array): T {\n util.assert(\n Array.isArray(tensors),\n () => 'The argument passed to tf.addN() must be a list of tensors');\n util.assert(\n tensors.length >= 1,\n () => `Must pass at least one tensor to tf.addN(), but got ` +\n `${tensors.length}`);\n\n const $tensors =\n tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN'));\n\n const firstTensor = $tensors[0];\n $tensors.forEach(t => {\n if (t.dtype !== firstTensor.dtype) {\n throw new Error(\n 'All tensors passed to tf.addN() must have the same dtype');\n }\n });\n\n $tensors.forEach(t => {\n if (!util.arraysEqual(t.shape, firstTensor.shape)) {\n throw new Error(\n 'All tensors passed to tf.addN() must have the same shape');\n }\n });\n\n const inputs: AddNInputs = $tensors;\n\n return ENGINE.runKernel(AddN, inputs as unknown as NamedTensorMap);\n}\n\nexport const addN = /* @__PURE__ */ op({addN_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {All, AllAttrs, AllInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical and of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.all().print(); // or tf.all(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.all(axis).print(); // or tf.all(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction all_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'all', 'bool');\n\n const inputs: AllInputs = {x: $x};\n const attrs: AllAttrs = {axis, keepDims};\n\n return ENGINE.runKernel(\n All, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const all = /* @__PURE__ */ op({all_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Any, AnyAttrs, AnyInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical or of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.any().print(); // or tf.any(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.any(axis).print(); // or tf.any(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction any_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'any', 'bool');\n\n const inputs: AnyInputs = {x: $x};\n const attrs: AnyAttrs = {axis, keepDims};\n\n return ENGINE.runKernel(\n Any, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\n// tslint:disable-next-line:variable-name\nexport const any = /* @__PURE__ */ op({any_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ArgMax, ArgMaxAttrs, ArgMaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the indices of the maximum values along an `axis`.\n *\n * The result has the same shape as `input` with the dimension along `axis`\n * removed.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.argMax().print(); // or tf.argMax(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);\n *\n * const axis = 1;\n * x.argMax(axis).print(); // or tf.argMax(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction argMax_(x: Tensor|TensorLike, axis = 0): T {\n const $x = convertToTensor(x, 'x', 'argMax');\n\n const inputs: ArgMaxInputs = {x: $x};\n const attrs: ArgMaxAttrs = {axis};\n\n return ENGINE.runKernel(\n ArgMax, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const argMax = /* @__PURE__ */ op({argMax_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ArgMin, ArgMinAttrs, ArgMinInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the indices of the minimum values along an `axis`.\n *\n * The result has the same shape as `input` with the dimension along `axis`\n * removed.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.argMin().print(); // or tf.argMin(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);\n *\n * const axis = 1;\n * x.argMin(axis).print(); // or tf.argMin(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction argMin_(x: Tensor|TensorLike, axis = 0): T {\n const $x = convertToTensor(x, 'x', 'argMin');\n\n const inputs: ArgMinInputs = {x: $x};\n const attrs: ArgMinAttrs = {axis};\n\n return ENGINE.runKernel(\n ArgMin, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const argMin = /* @__PURE__ */ op({argMin_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asin, AsinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes asin of the input `tf.Tensor` element-wise: `asin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asin().print(); // or tf.asin(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asin_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'asin');\n const inputs: AsinInputs = {x: $x};\n\n return ENGINE.runKernel(Asin, inputs as unknown as NamedTensorMap);\n}\nexport const asin = /* @__PURE__ */ op({asin_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asinh, AsinhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:\n * `asinh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asinh().print(); // or tf.asinh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asinh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'asinh');\n\n const inputs: AsinhInputs = {x: $x};\n\n return ENGINE.runKernel(Asinh, inputs as unknown as NamedTensorMap);\n}\nexport const asinh = /* @__PURE__ */ op({asinh_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan, AtanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes atan of the input `tf.Tensor` element-wise: `atan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.atan().print(); // or tf.atan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'atan');\n\n const inputs: AtanInputs = {x: $x};\n\n return ENGINE.runKernel(Atan, inputs as unknown as NamedTensorMap);\n}\nexport const atan = /* @__PURE__ */ op({atan_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan2, Atan2Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);\n * const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);\n *\n * tf.atan2(a, b).print()\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan2_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'atan2');\n let $b = convertToTensor(b, 'b', 'atan2');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: Atan2Inputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Atan2, inputs as unknown as NamedTensorMap);\n}\n\nexport const atan2 = /* @__PURE__ */ op({atan2_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atanh, AtanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:\n * `atanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.atanh().print(); // or tf.atanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atanh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'atanh');\n\n const inputs: AtanhInputs = {x: $x};\n\n return ENGINE.runKernel(Atanh, inputs as unknown as NamedTensorMap);\n}\nexport const atanh = /* @__PURE__ */ op({atanh_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\ntype PadType = 'SAME'|'VALID'|'NUMBER'|'EXPLICIT';\n\n// For NHWC should be in the following form:\n// [[0, 0], [pad_top,pad_bottom], [pad_left, pad_right], [0, 0]]\n// For NCHW should be in the following form:\n// [[0, 0], [0, 0], [pad_top,pad_bottom], [pad_left, pad_right]]\n// Reference: https://www.tensorflow.org/api_docs/python/tf/nn/conv2d\nexport type ExplicitPadding =\n [[number, number], [number, number], [number, number], [number, number]];\n\nexport type PadInfo = {\n top: number,\n left: number,\n right: number,\n bottom: number,\n type: PadType\n};\n\nexport type PadInfo3D = {\n top: number,\n left: number,\n right: number,\n bottom: number,\n front: number,\n back: number,\n type: PadType\n};\n\n/**\n * Information about the forward pass of a convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv2DInfo = {\n batchSize: number,\n inHeight: number,\n inWidth: number,\n inChannels: number,\n outHeight: number,\n outWidth: number,\n outChannels: number,\n dataFormat: 'channelsFirst'|'channelsLast',\n strideHeight: number,\n strideWidth: number,\n dilationHeight: number,\n dilationWidth: number,\n filterHeight: number,\n filterWidth: number,\n effectiveFilterHeight: number,\n effectiveFilterWidth: number,\n padInfo: PadInfo,\n inShape: [number, number, number, number],\n outShape: [number, number, number, number],\n filterShape: [number, number, number, number]\n};\n\n/**\n *\n * @param inputShape Input tensor shape is of the following dimensions:\n * `[batch, height, width, inChannels]`.\n * @param filterShape The filter shape is of the following dimensions:\n * `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n * input tensor: `[strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat The data format of the input and output data.\n * Defaults to 'NHWC'.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.\n * Defaults to `[1, 1]`. If `dilations` is a single number, then\n * `dilationHeight == dilationWidth`.\n */\nexport function computeDilation2DInfo(\n inputShape: [number, number, number, number],\n filterShape: [number, number, number], strides: number|[number, number],\n pad: 'same'|'valid'|number, dataFormat: 'NHWC' = 'NHWC',\n dilations: number|[number, number]) {\n // `computerConv2DInfo` require filterShape to be in the dimension of:\n // `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have\n // outDepth, it should have the same depth as the input.\n // Input shape: [batch, height, width, inChannels]\n const inputChannels = inputShape[3];\n const $filterShape =\n [...filterShape, inputChannels] as [number, number, number, number];\n const $dataFormat = convertConv2DDataFormat(dataFormat);\n\n return computeConv2DInfo(\n inputShape, $filterShape, strides, dilations, pad,\n null /* roundingMode */, null /* depthWise */, $dataFormat);\n}\n\nexport function computePool2DInfo(\n inShape: [number, number, number, number],\n filterSize: [number, number]|number, strides: number|[number, number],\n dilations: number|[number, number],\n pad: 'same'|'valid'|number|ExplicitPadding,\n roundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n const [filterHeight, filterWidth] = parseTupleParam(filterSize);\n\n let filterShape: [number, number, number, number];\n if (dataFormat === 'channelsLast') {\n filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];\n } else if (dataFormat === 'channelsFirst') {\n filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n return computeConv2DInfo(\n inShape, filterShape, strides, dilations, pad, roundingMode, false,\n dataFormat);\n}\n\n/**\n * Computes the information for a forward pass of a pooling3D operation.\n */\nexport function computePool3DInfo(\n inShape: [number, number, number, number, number],\n filterSize: number|[number, number, number],\n strides: number|[number, number, number],\n dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n roundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): Conv3DInfo {\n const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);\n\n let filterShape: [number, number, number, number, number];\n let $dataFormat: 'channelsFirst'|'channelsLast';\n if (dataFormat === 'NDHWC') {\n $dataFormat = 'channelsLast';\n filterShape =\n [filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];\n } else if (dataFormat === 'NCDHW') {\n $dataFormat = 'channelsFirst';\n filterShape =\n [filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n return computeConv3DInfo(\n inShape, filterShape, strides, dilations, pad, false, $dataFormat,\n roundingMode);\n}\n\n/**\n * Computes the information for a forward pass of a convolution/pooling\n * operation.\n */\nexport function computeConv2DInfo(\n inShape: [number, number, number, number],\n filterShape: [number, number, number, number],\n strides: number|[number, number], dilations: number|[number, number],\n pad: 'same'|'valid'|number|ExplicitPadding,\n roundingMode?: 'floor'|'round'|'ceil', depthwise = false,\n dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];\n if (dataFormat === 'channelsLast') {\n [batchSize, inHeight, inWidth, inChannels] = inShape;\n } else if (dataFormat === 'channelsFirst') {\n [batchSize, inChannels, inHeight, inWidth] = inShape;\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n const [filterHeight, filterWidth, , filterChannels] = filterShape;\n const [strideHeight, strideWidth] = parseTupleParam(strides);\n const [dilationHeight, dilationWidth] = parseTupleParam(dilations);\n\n const effectiveFilterHeight =\n getEffectiveFilterSize(filterHeight, dilationHeight);\n const effectiveFilterWidth =\n getEffectiveFilterSize(filterWidth, dilationWidth);\n const {padInfo, outHeight, outWidth} = getPadAndOutInfo(\n pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight,\n effectiveFilterWidth, roundingMode, dataFormat);\n\n const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n let outShape: [number, number, number, number];\n if (dataFormat === 'channelsFirst') {\n outShape = [batchSize, outChannels, outHeight, outWidth];\n } else if (dataFormat === 'channelsLast') {\n outShape = [batchSize, outHeight, outWidth, outChannels];\n }\n\n return {\n batchSize,\n dataFormat,\n inHeight,\n inWidth,\n inChannels,\n outHeight,\n outWidth,\n outChannels,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n effectiveFilterHeight,\n effectiveFilterWidth,\n dilationHeight,\n dilationWidth,\n inShape,\n outShape,\n filterShape\n };\n}\n\n/**\n * Information about the forward pass of a 3D convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv3DInfo = {\n batchSize: number,\n inDepth: number,\n inHeight: number,\n inWidth: number,\n inChannels: number,\n outDepth: number,\n outHeight: number,\n outWidth: number,\n outChannels: number,\n dataFormat: 'channelsFirst'|'channelsLast',\n strideDepth: number,\n strideHeight: number,\n strideWidth: number,\n dilationDepth: number,\n dilationHeight: number,\n dilationWidth: number,\n filterDepth: number,\n filterHeight: number,\n filterWidth: number,\n effectiveFilterDepth: number,\n effectiveFilterHeight: number,\n effectiveFilterWidth: number,\n padInfo: PadInfo3D,\n inShape: [number, number, number, number, number],\n outShape: [number, number, number, number, number],\n filterShape: [number, number, number, number, number]\n};\n\n/**\n * Computes the information for a forward pass of a 3D convolution/pooling\n * operation.\n */\nexport function computeConv3DInfo(\n inShape: [number, number, number, number, number],\n filterShape: [number, number, number, number, number],\n strides: number|[number, number, number],\n dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n depthwise = false,\n dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast',\n roundingMode?: 'floor'|'round'|'ceil'): Conv3DInfo {\n let [batchSize, inDepth, inHeight, inWidth, inChannels] =\n [-1, -1, -1, -1, -1];\n if (dataFormat === 'channelsLast') {\n [batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;\n } else if (dataFormat === 'channelsFirst') {\n [batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n\n const [filterDepth, filterHeight, filterWidth, , filterChannels] =\n filterShape;\n const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);\n const [dilationDepth, dilationHeight, dilationWidth] =\n parse3TupleParam(dilations);\n\n const effectiveFilterDepth =\n getEffectiveFilterSize(filterDepth, dilationDepth);\n const effectiveFilterHeight =\n getEffectiveFilterSize(filterHeight, dilationHeight);\n const effectiveFilterWidth =\n getEffectiveFilterSize(filterWidth, dilationWidth);\n const {padInfo, outDepth, outHeight, outWidth} = get3DPadAndOutInfo(\n pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth,\n effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth,\n roundingMode);\n\n const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n let outShape: [number, number, number, number, number];\n if (dataFormat === 'channelsFirst') {\n outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];\n } else if (dataFormat === 'channelsLast') {\n outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];\n }\n\n return {\n batchSize,\n dataFormat,\n inDepth,\n inHeight,\n inWidth,\n inChannels,\n outDepth,\n outHeight,\n outWidth,\n outChannels,\n padInfo,\n strideDepth,\n strideHeight,\n strideWidth,\n filterDepth,\n filterHeight,\n filterWidth,\n effectiveFilterDepth,\n effectiveFilterHeight,\n effectiveFilterWidth,\n dilationDepth,\n dilationHeight,\n dilationWidth,\n inShape,\n outShape,\n filterShape\n };\n}\n\nfunction computeOutputShape2D(\n inShape: [number, number], fieldSize: number, stride: number,\n zeroPad?: number, roundingMode?: 'floor'|'round'|'ceil'): [number, number] {\n if (zeroPad == null) {\n zeroPad = computeDefaultPad(inShape, fieldSize, stride);\n }\n const inputRows = inShape[0];\n const inputCols = inShape[1];\n\n const outputRows =\n round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n const outputCols =\n round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n\n return [outputRows, outputCols];\n}\n\nfunction computeOutputShape4D(\n inShape: [number, number, number, number],\n filterShape: [number, number, number], outChannels: number,\n strides: [number, number, number], zeroPad?: number,\n roundingMode?: 'floor'|'round'|'ceil'): [number, number, number, number] {\n if (zeroPad == null) {\n zeroPad = computeDefaultPad(inShape, filterShape[0], strides[0]);\n }\n const outShape: [number, number, number, number] = [0, 0, 0, outChannels];\n for (let index = 0; index < 3; index++) {\n if (inShape[index] + 2 * zeroPad >= filterShape[index]) {\n outShape[index] = round(\n (inShape[index] - filterShape[index] + 2 * zeroPad) / strides[index] +\n 1,\n roundingMode);\n }\n }\n return outShape;\n}\n\nexport function computeDefaultPad(\n inputShape: [number, number]|[number, number, number, number],\n fieldSize: number, stride: number, dilation = 1): number {\n const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);\n return Math.floor(\n (inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);\n}\n\nfunction parseTupleParam(param: number|number[]): [number, number, number] {\n if (typeof param === 'number') {\n return [param, param, param];\n }\n if (param.length === 2) {\n return [param[0], param[1], 1];\n }\n return param as [number, number, number];\n}\n\nfunction parse3TupleParam(param: number|[number, number, number]):\n [number, number, number] {\n return typeof param === 'number' ? [param, param, param] : param;\n}\n\n/* See https://www.tensorflow.org/api_docs/python/tf/nn/atrous_conv2d\n * Atrous convolution is equivalent to standard convolution with upsampled\n * filters with effective_filter_height =\n * filter_height + (filter_height - 1) * (dilation - 1)\n * and effective_filter_width =\n * filter_width + (filter_width - 1) * (dilation - 1),\n * produced by inserting dilation - 1 zeros along consecutive elements across\n * the filters' spatial dimensions.\n * When there is a dilation, this converts a filter dimension to the\n * effective filter dimension, so it can be used in a standard convolution.\n */\nfunction getEffectiveFilterSize(filterSize: number, dilation: number) {\n if (dilation <= 1) {\n return filterSize;\n }\n\n return filterSize + (filterSize - 1) * (dilation - 1);\n}\n\nfunction getPadAndOutInfo(\n pad: 'same'|'valid'|number|ExplicitPadding, inHeight: number,\n inWidth: number, strideHeight: number, strideWidth: number,\n filterHeight: number, filterWidth: number,\n roundingMode: 'floor'|'round'|'ceil',\n dataFormat: 'channelsFirst'|\n 'channelsLast'): {padInfo: PadInfo, outHeight: number, outWidth: number} {\n let padInfo: PadInfo;\n let outHeight: number;\n let outWidth: number;\n\n if (typeof pad === 'number') {\n const padType = (pad === 0) ? 'VALID' : 'NUMBER';\n padInfo = {top: pad, bottom: pad, left: pad, right: pad, type: padType};\n const outShape = computeOutputShape2D(\n [inHeight, inWidth], filterHeight, strideHeight, pad, roundingMode);\n outHeight = outShape[0];\n outWidth = outShape[1];\n } else if (pad === 'same') {\n outHeight = Math.ceil(inHeight / strideHeight);\n outWidth = Math.ceil(inWidth / strideWidth);\n const padAlongHeight =\n Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);\n const padAlongWidth =\n Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);\n const top = Math.floor(padAlongHeight / 2);\n const bottom = padAlongHeight - top;\n const left = Math.floor(padAlongWidth / 2);\n const right = padAlongWidth - left;\n padInfo = {top, bottom, left, right, type: 'SAME'};\n } else if (pad === 'valid') {\n padInfo = {top: 0, bottom: 0, left: 0, right: 0, type: 'VALID'};\n outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);\n outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);\n } else if (typeof pad === 'object') {\n const top = dataFormat === 'channelsLast' ? pad[1][0] : pad[2][0];\n const bottom = dataFormat === 'channelsLast' ? pad[1][1] : pad[2][1];\n const left = dataFormat === 'channelsLast' ? pad[2][0] : pad[3][0];\n const right = dataFormat === 'channelsLast' ? pad[2][1] : pad[3][1];\n const padType = (top === 0 && bottom === 0 && left === 0 && right === 0) ?\n 'VALID' :\n 'EXPLICIT';\n padInfo = {top, bottom, left, right, type: padType};\n outHeight = round(\n (inHeight - filterHeight + top + bottom) / strideHeight + 1,\n roundingMode);\n outWidth = round(\n (inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);\n } else {\n throw Error(`Unknown padding parameter: ${pad}`);\n }\n return {padInfo, outHeight, outWidth};\n}\n\nfunction get3DPadAndOutInfo(\n pad: 'same'|'valid'|number, inDepth: number, inHeight: number,\n inWidth: number, strideDepth: number, strideHeight: number,\n strideWidth: number, filterDepth: number, filterHeight: number,\n filterWidth: number, roundingMode?: 'floor'|'round'|'ceil'): {\n padInfo: PadInfo3D,\n outDepth: number,\n outHeight: number,\n outWidth: number\n} {\n let padInfo: PadInfo3D;\n let outDepth: number;\n let outHeight: number;\n let outWidth: number;\n\n if (pad === 'valid') {\n pad = 0;\n }\n\n if (typeof pad === 'number') {\n const padType = (pad === 0) ? 'VALID' : 'NUMBER';\n padInfo = {\n top: pad,\n bottom: pad,\n left: pad,\n right: pad,\n front: pad,\n back: pad,\n type: padType\n };\n const outShape = computeOutputShape4D(\n [inDepth, inHeight, inWidth, 1],\n [filterDepth, filterHeight, filterWidth], 1,\n [strideDepth, strideHeight, strideWidth], pad, roundingMode);\n outDepth = outShape[0];\n outHeight = outShape[1];\n outWidth = outShape[2];\n } else if (pad === 'same') {\n outDepth = Math.ceil(inDepth / strideDepth);\n outHeight = Math.ceil(inHeight / strideHeight);\n outWidth = Math.ceil(inWidth / strideWidth);\n const padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;\n const padAlongHeight =\n (outHeight - 1) * strideHeight + filterHeight - inHeight;\n const padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;\n const front = Math.floor(padAlongDepth / 2);\n const back = padAlongDepth - front;\n const top = Math.floor(padAlongHeight / 2);\n const bottom = padAlongHeight - top;\n const left = Math.floor(padAlongWidth / 2);\n const right = padAlongWidth - left;\n\n padInfo = {top, bottom, left, right, front, back, type: 'SAME'};\n } else {\n throw Error(`Unknown padding parameter: ${pad}`);\n }\n return {padInfo, outDepth, outHeight, outWidth};\n}\n\n/**\n * Rounds a value depending on the rounding mode\n * @param value\n * @param roundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction round(value: number, roundingMode?: 'floor'|'round'|'ceil') {\n if (!roundingMode) {\n return Math.trunc(value);\n }\n switch (roundingMode) {\n case 'round':\n // used for Caffe Conv\n return Math.round(value);\n case 'ceil':\n // used for Caffe Pool\n return Math.ceil(value);\n case 'floor':\n return Math.floor(value);\n default:\n throw new Error(`Unknown roundingMode ${roundingMode}`);\n }\n}\n\nexport function tupleValuesAreOne(param: number|number[]): boolean {\n const [dimA, dimB, dimC] = parseTupleParam(param);\n return dimA === 1 && dimB === 1 && dimC === 1;\n}\n\nexport function eitherStridesOrDilationsAreOne(\n strides: number|number[], dilations: number|number[]): boolean {\n return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);\n}\n\nexport function stridesOrDilationsArePositive(values: number|\n number[]): boolean {\n return parseTupleParam(values).every(value => value > 0);\n}\n\n/**\n * Convert Conv2D dataFormat from 'NHWC'|'NCHW' to\n * 'channelsLast'|'channelsFirst'\n * @param dataFormat in 'NHWC'|'NCHW' mode\n * @return dataFormat in 'channelsLast'|'channelsFirst' mode\n * @throws unknown dataFormat\n */\nexport function convertConv2DDataFormat(dataFormat: 'NHWC'|'NCHW'):\n 'channelsLast'|'channelsFirst' {\n if (dataFormat === 'NHWC') {\n return 'channelsLast';\n } else if (dataFormat === 'NCHW') {\n return 'channelsFirst';\n } else {\n throw new Error(`Unknown dataFormat ${dataFormat}`);\n }\n}\n\n/**\n * Check validity of pad when using dimRoundingMode.\n * @param opDesc A string of op description\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid` output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @throws unknown padding parameter\n */\nexport function checkPadOnDimRoundingMode(\n opDesc: string, pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil') {\n if (dimRoundingMode != null) {\n if (typeof pad === 'string') {\n throw Error(\n `Error in ${opDesc}: pad must be an integer when using ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n } else if (typeof pad === 'number') {\n util.assert(\n util.isInt(pad),\n () => `Error in ${opDesc}: pad must be an integer when using ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n } else if (typeof pad === 'object') {\n (pad as ExplicitPadding).forEach(p => {\n p.forEach(v => {\n util.assert(\n util.isInt(v),\n () => `Error in ${opDesc}: pad must be an integer when using ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${v}.`);\n });\n });\n } else {\n throw Error(`Error in ${opDesc}: Unknown padding parameter: ${pad}`);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reshape, ReshapeAttrs, ReshapeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reshapes a `tf.Tensor` to a given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * If one component of shape is the special value -1, the size of that\n * dimension is computed so that the total size remains constant. In\n * particular, a shape of [-1] flattens into 1-D. At most one component of\n * shape can be -1.\n *\n * If shape is 1-D or higher, then the operation returns a tensor with shape\n * shape filled with the values of tensor. In this case, the number of\n * elements implied by shape must be the same as the number of elements in\n * tensor.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.reshape([2, 2]).print();\n * ```\n *\n * @param x The input tensor to be reshaped.\n * @param shape An array of integers defining the output tensor shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction reshape_(\n x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor {\n const $x = convertToTensor(x, 'x', 'reshape', 'string_or_numeric');\n\n const inputs: ReshapeInputs = {x: $x};\n const attrs: ReshapeAttrs = {shape};\n return ENGINE.runKernel(\n Reshape, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\nexport const reshape = /* @__PURE__ */ op({reshape_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool, AvgPoolAttrs, AvgPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D average pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction avgPool_(\n x: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'avgPool', 'float32');\n const dilations = 1;\n\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);\n conv_util.checkPadOnDimRoundingMode('avgPool', pad, dimRoundingMode);\n const inputs: AvgPoolInputs = {x: x4D};\n const attrs: AvgPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res = ENGINE.runKernel(\n AvgPool, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n res = cast(res, $x.dtype);\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n\n return res;\n}\n\nexport const avgPool = /* @__PURE__ */ op({avgPool_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D average pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.avgPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n * `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n * `[filterDepth, filterHeight, filterWidth]`.\n * If `filterSize` is a single number,\n * then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n * `[strideDepth, strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n * \"NDHWC\". Specify the data format of the input and output data. With the\n * default format \"NDHWC\", the data is stored in the order of: [batch,\n * depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction avgPool3d_(\n x: T|TensorLike, filterSize: [number, number, number]|number,\n strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');\n\n let x5D = $x as Tensor5D;\n let reshapedTo5D = false;\n if ($x.rank === 4) {\n reshapedTo5D = true;\n x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n }\n\n util.assert(\n x5D.rank === 5,\n () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n util.assert(\n dataFormat === 'NDHWC',\n () => `Error in avgPool3d: Only NDHWC is currently supported, ` +\n `but got dataFormat of ${dataFormat}`);\n util.assert(\n (typeof strides === 'number' && strides > 0) ||\n (Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 &&\n strides[2] > 0),\n () => `Error in avgPool3d: Stride must be > 0, but got '${strides}'`);\n checkPadOnDimRoundingMode('avgPool3d', pad, dimRoundingMode);\n const inputs: AvgPool3DInputs = {x: x5D};\n const attrs:\n AvgPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res = ENGINE.runKernel(\n AvgPool3D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n res = cast(res, x5D.dtype);\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n\n return res;\n}\n\nexport const avgPool3d = /* @__PURE__ */ op({avgPool3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Concat, ConcatAttrs, ConcatInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {clone} from './clone';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor`s along a given axis.\n *\n * The tensors ranks and types must match, and their sizes must match in all\n * dimensions except `axis`.\n *\n * Also available are stricter rank-specific methods that assert that\n * `tensors` are of the given rank:\n * - `tf.concat1d`\n * - `tf.concat2d`\n * - `tf.concat3d`\n * - `tf.concat4d`\n *\n * Except `tf.concat1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * a.concat(b).print(); // or a.concat(b)\n * ```\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.concat([a, b, c]).print();\n * ```\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [10, 20]]);\n * const b = tf.tensor2d([[3, 4], [30, 40]]);\n * const axis = 1;\n * tf.concat([a, b], axis).print();\n * ```\n * @param tensors A list of tensors to concatenate.\n * @param axis The axis to concatenate along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction concat_(tensors: Array, axis = 0): T {\n assert(tensors.length >= 1, () => 'Pass at least one tensor to concat');\n\n const $tensors =\n convertToTensorArray(tensors, 'tensors', 'concat', 'string_or_numeric');\n\n if ($tensors[0].dtype === 'complex64') {\n $tensors.forEach(tensor => {\n if (tensor.dtype !== 'complex64') {\n throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${tensor.dtype}. `);\n }\n });\n }\n\n if ($tensors.length === 1) {\n return clone($tensors[0]);\n }\n\n const inputs: ConcatInputs = $tensors;\n const attr: ConcatAttrs = {axis};\n\n return ENGINE.runKernel(\n Concat, inputs as unknown as NamedTensorMap,\n attr as unknown as NamedAttrMap);\n}\n\nexport const concat = /* @__PURE__ */ op({concat_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sigmoid', 'float32');\n\n const inputs: SigmoidInputs = {x: $x};\n\n return ENGINE.runKernel(Sigmoid, inputs as unknown as NamedTensorMap);\n}\nexport const sigmoid = /* @__PURE__ */ op({sigmoid_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Slice, SliceAttrs, SliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a slice from a `tf.Tensor` starting at coordinates `begin`\n * and is of size `size`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `x` is of the given rank:\n * - `tf.slice1d`\n * - `tf.slice2d`\n * - `tf.slice3d`\n * - `tf.slice4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.slice([1], [2]).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * x.slice([1, 0], [1, 2]).print();\n * ```\n * @param x The input `tf.Tensor` to slice from.\n * @param begin The coordinates to start the slice from. The length can be\n * less than the rank of x - the rest of the axes will have implicit 0 as\n * start. Can also be a single number, in which case it specifies the\n * first axis.\n * @param size The size of the slice. The length can be less than the rank of\n * x - the rest of the axes will have implicit -1. A value of -1 requests\n * the rest of the dimensions in the axis. Can also be a single number,\n * in which case it specifies the size of the first axis.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction slice_>(\n x: T|TensorLike, begin: number|number[], size?: number|number[]): T {\n const $x = convertToTensor(x, 'x', 'slice', 'string_or_numeric');\n\n if ($x.rank === 0) {\n throw new Error('Slicing scalar is not possible');\n }\n\n const inputs: SliceInputs = {x: $x};\n const attrs: SliceAttrs = {begin, size};\n\n return ENGINE.runKernel(\n Slice, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const slice = /* @__PURE__ */ op({slice_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tanh, TanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, 70]);\n *\n * x.tanh().print(); // or tf.tanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tanh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'tanh', 'float32');\n\n const inputs: TanhInputs = {x: $x};\n\n return ENGINE.runKernel(Tanh, inputs as unknown as NamedTensorMap);\n}\nexport const tanh = /* @__PURE__ */ op({tanh_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {add} from './add';\nimport {concat} from './concat';\nimport {matMul} from './mat_mul';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {slice} from './slice';\nimport {tanh} from './tanh';\n\n/**\n * Computes the next state and output of a BasicLSTMCell.\n *\n * Returns `[newC, newH]`.\n *\n * Derived from tf.contrib.rnn.BasicLSTMCell.\n *\n * @param forgetBias Forget bias for the cell.\n * @param lstmKernel The weights for the cell.\n * @param lstmBias The bias for the cell.\n * @param data The input to the cell.\n * @param c Previous cell state.\n * @param h Previous cell output.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction basicLSTMCell_(\n forgetBias: Scalar|TensorLike, lstmKernel: Tensor2D|TensorLike,\n lstmBias: Tensor1D|TensorLike, data: Tensor2D|TensorLike,\n c: Tensor2D|TensorLike, h: Tensor2D|TensorLike): [Tensor2D, Tensor2D] {\n const $forgetBias =\n convertToTensor(forgetBias, 'forgetBias', 'basicLSTMCell');\n const $lstmKernel =\n convertToTensor(lstmKernel, 'lstmKernel', 'basicLSTMCell');\n const $lstmBias = convertToTensor(lstmBias, 'lstmBias', 'basicLSTMCell');\n const $data = convertToTensor(data, 'data', 'basicLSTMCell');\n const $c = convertToTensor(c, 'c', 'basicLSTMCell');\n const $h = convertToTensor(h, 'h', 'basicLSTMCell');\n\n const combined = concat([$data, $h], 1);\n const weighted = matMul(combined, $lstmKernel);\n const res: Tensor2D = add(weighted, $lstmBias);\n\n // i = input_gate, j = new_input, f = forget_gate, o = output_gate\n const batchSize = res.shape[0];\n const sliceCols = res.shape[1] / 4;\n const sliceSize: [number, number] = [batchSize, sliceCols];\n const i = slice(res, [0, 0], sliceSize);\n const j = slice(res, [0, sliceCols], sliceSize);\n const f = slice(res, [0, sliceCols * 2], sliceSize);\n const o = slice(res, [0, sliceCols * 3], sliceSize);\n\n const newC: Tensor2D =\n add(mul(sigmoid(i), tanh(j)),\n mul($c, sigmoid(add($forgetBias, f)) as Tensor2D));\n const newH: Tensor2D = mul(tanh(newC), sigmoid(o));\n return [newC, newH];\n}\n\nexport const basicLSTMCell = /* @__PURE__ */ op({basicLSTMCell_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of\n * shape `blockShape + [batch]`, interleaves these blocks back into the grid\n * defined by the spatial dimensions `[1, ..., M]`, to obtain a result with\n * the same rank as the input. The spatial dimensions of this intermediate\n * result are then optionally cropped according to `crops` to produce the\n * output. This is the reverse of `tf.spaceToBatchND`. See below for a precise\n * description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);\n * const blockShape = [2, 2];\n * const crops = [[0, 0], [0, 0]];\n *\n * x.batchToSpaceND(blockShape, crops).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.\n * `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input\n * dimension `i + 1`, which corresponds to spatial dimension `i`. It is required\n * that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,\n * blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,\n * x.shape[N-1]]`\n *\n * 2. Permute dimensions of `reshaped` to produce `permuted` of shape `[batch /\n * prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`\n * according to `crops` to produce the output of shape: `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],\n * ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -\n * crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction batchToSpaceND_(\n x: T|TensorLike, blockShape: number[], crops: number[][]): T {\n const $x = convertToTensor(x, 'x', 'batchToSpaceND');\n const prod = blockShape.reduce((a, b) => a * b);\n\n util.assert(\n $x.rank >= 1 + blockShape.length,\n () => `input rank is ${$x.rank} but should be > than blockShape.length ${\n blockShape.length}`);\n\n util.assert(\n crops.length === blockShape.length,\n () => `crops.length is ${\n crops.length} but should be equal to blockShape.length ${\n blockShape.length}`);\n\n util.assert(\n $x.shape[0] % prod === 0,\n () => `input tensor batch is ${\n $x.shape[0]} but is not divisible by the product of ` +\n `the elements of blockShape ${blockShape.join(' * ')} === ${prod}`);\n\n const inputs: BatchToSpaceNDInputs = {x: $x};\n const attrs: BatchToSpaceNDAttrs = {blockShape, crops};\n\n return ENGINE.runKernel(\n BatchToSpaceND, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const batchToSpaceND = /* @__PURE__ */ op({batchToSpaceND_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {xAs4D} from './batchnorm_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Batch normalization.\n *\n * As described in\n * [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).\n *\n * Mean, variance, scale, and offset can be of two shapes:\n * - The same shape as the input.\n * - In the common case, the depth dimension is the last dimension of x, so\n * the values would be a `tf.Tensor1D` of shape [depth].\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that parameters passed are of given rank\n * - `tf.batchNorm2d`\n * - `tf.batchNorm3d`\n * - `tf.batchNorm4d`\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction batchNorm_(\n x: Tensor|TensorLike, mean: Tensor|Tensor1D|TensorLike,\n variance: Tensor|Tensor1D|TensorLike,\n offset?: Tensor|Tensor1D|TensorLike,\n scale?: Tensor|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor {\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|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n\n util.assert(\n $mean.rank === $variance.rank,\n () => 'Batch normalization gradient requires mean and variance to have ' +\n 'equal ranks.');\n util.assert(\n $offset == null || $mean.rank === $offset.rank,\n () => 'Batch normalization gradient requires mean and offset to have ' +\n 'equal ranks.');\n util.assert(\n $scale == null || $mean.rank === $scale.rank,\n () => 'Batch normalization gradient requires mean and scale to have ' +\n 'equal ranks.');\n\n const x4D: Tensor4D = xAs4D($x);\n\n const inputs: FusedBatchNormInputs = {\n x: x4D,\n scale: $scale,\n offset: $offset,\n mean: $mean,\n variance: $variance\n };\n\n const attrs: FusedBatchNormAttrs = {varianceEpsilon};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n FusedBatchNorm, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor;\n\n return reshape(res, $x.shape);\n}\n\nexport const batchNorm = /* @__PURE__ */ op({batchNorm_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, Tensor4D} from '../tensor';\nimport {Rank} from '../types';\nimport {reshape} from './reshape';\n\nexport function xAs4D(x: Tensor) {\n let x4D: Tensor4D;\n if (x.rank === 0 || x.rank === 1) {\n x4D = reshape(x, [1, 1, 1, x.size]);\n } else if (x.rank === 2) {\n x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);\n } else if (x.rank === 3) {\n x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n } else {\n x4D = x as Tensor4D;\n }\n\n return x4D;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 2D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm2d_(\n x: Tensor2D|TensorLike, mean: Tensor2D|Tensor1D|TensorLike,\n variance: Tensor2D|Tensor1D|TensorLike,\n offset?: Tensor2D|Tensor1D|TensorLike, scale?: Tensor2D|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor2D {\n const $x = convertToTensor(x, 'x', 'batchNorm');\n const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n let $scale: Tensor2D|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor2D|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n util.assert(\n $x.rank === 2,\n () => `Error in batchNorm2D: x must be rank 2 but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $mean.rank === 2 || $mean.rank === 1,\n () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but ` +\n `got rank ${$mean.rank}.`);\n util.assert(\n $variance.rank === 2 || $variance.rank === 1,\n () => `Error in batchNorm2D: variance must be rank 2 or rank 1 ` +\n `but got rank ${$variance.rank}.`);\n if ($scale != null) {\n util.assert(\n $scale.rank === 2 || $scale.rank === 1,\n () => `Error in batchNorm2D: scale must be rank 2 or rank 1 ` +\n `but got rank ${$scale.rank}.`);\n }\n if ($offset != null) {\n util.assert(\n $offset.rank === 2 || $offset.rank === 1,\n () => `Error in batchNorm2D: offset must be rank 2 or rank 1 ` +\n `but got rank ${$offset.rank}.`);\n }\n\n return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm2d = /* @__PURE__ */ op({batchNorm2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 3D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm3d_(\n x: Tensor3D|TensorLike, mean: Tensor3D|Tensor1D|TensorLike,\n variance: Tensor3D|Tensor1D|TensorLike,\n offset?: Tensor3D|Tensor1D|TensorLike, scale?: Tensor3D|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor3D {\n const $x = convertToTensor(x, 'x', 'batchNorm');\n const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n let $scale: Tensor3D|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor3D|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n util.assert(\n $x.rank === 3,\n () => `Error in batchNorm3D: x must be rank 3 but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $mean.rank === 3 || $mean.rank === 1,\n () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but ` +\n `got rank ${$mean.rank}.`);\n util.assert(\n $variance.rank === 3 || $variance.rank === 1,\n () => `Error in batchNorm3D: variance must be rank 3 or rank 1 ` +\n `but got rank ${$variance.rank}.`);\n if ($scale != null) {\n util.assert(\n $scale.rank === 3 || $scale.rank === 1,\n () => `Error in batchNorm3D: scale must be rank 3 or rank 1 ` +\n `but got rank ${$scale.rank}.`);\n }\n if ($offset != null) {\n util.assert(\n $offset.rank === 3 || $offset.rank === 1,\n () => `Error in batchNorm3D: offset must be rank 3 or rank 1 ` +\n `but got rank ${$offset.rank}.`);\n }\n\n return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm3d = /* @__PURE__ */ op({batchNorm3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 4D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm4d_(\n x: Tensor4D|TensorLike, mean: Tensor4D|Tensor1D|TensorLike,\n variance: Tensor4D|Tensor1D|TensorLike,\n offset?: Tensor4D|Tensor1D|TensorLike, scale?: Tensor4D|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor4D {\n const $x = convertToTensor(x, 'x', 'batchNorm');\n const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n let $scale: Tensor4D|Tensor1D;\n if (scale != null) {\n $scale = convertToTensor(scale, 'scale', 'batchNorm');\n }\n let $offset: Tensor4D|Tensor1D;\n if (offset != null) {\n $offset = convertToTensor(offset, 'offset', 'batchNorm');\n }\n util.assert(\n $x.rank === 4,\n () => `Error in batchNorm4D: x must be rank 4 but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $mean.rank === 4 || $mean.rank === 1,\n () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but ` +\n `got rank ${$mean.rank}.`);\n util.assert(\n $variance.rank === 4 || $variance.rank === 1,\n () => `Error in batchNorm4D: variance must be rank 4 or rank 1 ` +\n `but got rank ${$variance.rank}.`);\n if ($scale != null) {\n util.assert(\n $scale.rank === 4 || $scale.rank === 1,\n () => `Error in batchNorm4D: scale must be rank 4 or rank 1 ` +\n `but got rank ${$scale.rank}.`);\n }\n if ($offset != null) {\n util.assert(\n $offset.rank === 4 || $offset.rank === 1,\n () => `Error in batchNorm4D: offset must be rank 4 or rank 1 ` +\n `but got rank ${$offset.rank}.`);\n }\n return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm4d = /* @__PURE__ */ op({batchNorm4d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Bincount, BincountAttrs, BincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1.\n * @param weights The weights tensor, must have the same shape as x, or a\n * length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction bincount_(\n x: T|TensorLike, weights: T|TensorLike, size: number): T {\n const $x = convertToTensor(x, 'x', 'bincount');\n const $weights = convertToTensor(weights, 'weights', 'bincount');\n\n util.assert(\n $x.dtype === 'int32',\n () => `Error in bincount: input ` +\n `dtype must be int32, but got ${$x.dtype}`);\n util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n util.assert(\n $weights.size === $x.size || $weights.size === 0,\n () => `Error in bincount: weights must have the same size as input or` +\n `0-length, but got input shape: ${$x.shape}, weights shape: ` +\n `${$weights.shape}.`);\n\n const inputs: BincountInputs = {x: $x, weights: $weights};\n const attrs: BincountAttrs = {size};\n\n return ENGINE.runKernel(\n Bincount, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const bincount = /* @__PURE__ */ op({bincount_});\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BitwiseAnd, BitwiseAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank} from '../types';\nimport {arraysEqual} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Bitwise `AND` operation for input tensors.\n *\n * Given two input tensors, returns a new tensor\n * with the `AND` calculated values.\n *\n * The method supports int32 values\n *\n *\n * ```js\n * const x = tf.tensor1d([0, 5, 3, 14], 'int32');\n * const y = tf.tensor1d([5, 0, 7, 11], 'int32');\n * tf.bitwiseAnd(x, y).print();\n * ```\n *\n * @param x The input tensor to be calculated.\n * @param y The input tensor to be calculated.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction bitwiseAnd_(x: Tensor, y: Tensor): Tensor {\n const $x = convertToTensor(x, 'x', 'bitwiseAnd');\n const $y = convertToTensor(y, 'y', 'bitwiseAnd');\n\n if (!arraysEqual($x.shape, $y.shape)) {\n throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${\n $x.shape}, y: ${$y.shape}`);\n }\n if ($x.dtype !== 'int32' || $y.dtype !== 'int32') {\n throw new Error(\n `BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${\n $x.dtype} and type of y: ${$y.dtype}`);\n }\n\n const inputs: BitwiseAndInputs = {a: $x, b: $y};\n return ENGINE.runKernel(BitwiseAnd, inputs as unknown as NamedTensorMap);\n}\nexport const bitwiseAnd = /* @__PURE__ */ op({bitwiseAnd_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { NamedTensorMap } from '../tensor_types';\nimport { ENGINE } from '../engine';\nimport { BroadcastArgs, BroadcastArgsInputs } from '../kernel_names';\nimport { Tensor } from '../tensor';\nimport { convertToTensor } from '../tensor_util_env';\nimport { Rank, TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Return the shape of s0 op s1 with broadcast.\n *\n * compute r0, the broadcasted shape as a tensor.\n * s0, s1 and r0 are all integer vectors.\n *\n * This function returns the shape of the result of an operation between\n * two tensors of size s0 and s1 performed with broadcast.\n *\n * @param s0 A tensor representing a shape\n * @param s1 A tensor representing a shape\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastArgs_(\n s0: Tensor | TensorLike, s1: Tensor | TensorLike): Tensor {\n const shape1Input = convertToTensor(s0, 's0', 'broadcastArgs', 'int32');\n const shape2Input = convertToTensor(s1, 's1', 'broadcastArgs', 'int32');\n\n if (shape1Input.rank !== 1) {\n throw new Error(\n 'broadcastArgs(): first input must be a vector (rank=1). ' +\n `Has rank ${shape1Input.rank}`);\n }\n\n if (shape2Input.rank !== 1) {\n throw new Error(\n 'broadcastArgs(): second input must be a vector (rank=1). ' +\n `Has rank ${shape2Input.rank}`);\n }\n\n const inputs: BroadcastArgsInputs = { s0: shape1Input, s1: shape2Input };\n return ENGINE.runKernel(BroadcastArgs, inputs as unknown as NamedTensorMap);\n}\n\nexport const broadcastArgs = /* @__PURE__ */ op({ broadcastArgs_ });\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {clone} from './clone';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Broadcast an array to a compatible shape NumPy-style.\n *\n * The tensor's shape is compared to the broadcast shape from end to beginning.\n * Ones are prepended to the tensor's shape until it has the same length as\n * the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is\n * already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then\n * the input tensor is tiled N times along that axis (using tf.tile).\n *\n * @param input The tensor that is to be broadcasted.\n * @param shape The input is to be broadcast to this shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastTo_(\n x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor {\n let input = convertToTensor(x, 'broadcastTo', 'x');\n const xShape = input.shape;\n\n assertNonNegativeIntegerDimensions(shape);\n\n if (shape.length < input.rank) {\n throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${\n input.rank}.`);\n }\n\n if (shape.length > input.rank) {\n const newShape = input.shape.slice();\n while (newShape.length < shape.length) {\n newShape.unshift(1);\n }\n input = reshape(input, newShape);\n }\n\n const inputShape = input.shape;\n const reps: number[] = Array.from(shape);\n for (let i = shape.length - 1; i >= 0; i--) {\n if (inputShape[i] === shape[i]) {\n reps[i] = 1;\n } else if (input.shape[i] !== 1) {\n throw new Error(\n `broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);\n }\n }\n const axes = reps.map((n, i) => n > 1 ? i : -1).filter(i => i >= 0);\n\n if (axes.length === 0) {\n return clone(input) as Tensor;\n }\n\n // TODO call broadcastTo kernel directly once backends implement broadcstTo\n const inputs: TileInputs = {x: input};\n const attrs: TileAttrs = {reps};\n return ENGINE.runKernel(\n Tile, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const broadcastTo = /* @__PURE__ */ op({broadcastTo_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Ceil, CeilInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.ceil().print(); // or tf.ceil(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction ceil_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'ceil', 'float32');\n\n const inputs: CeilInputs = {x: $x};\n return ENGINE.runKernel(Ceil, inputs as unknown as NamedTensorMap);\n}\nexport const ceil = /* @__PURE__ */ op({ceil_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {fill} from './fill';\n\nimport {op} from './operation';\n\n/**\n * Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)\n * ```\n * @param x The input tensor.\n * @param clipValueMin Lower bound of range to be clipped to.\n * @param clipValueMax Upper bound of range to be clipped to.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction clipByValue_(\n x: T|TensorLike, clipValueMin: number, clipValueMax: number): T {\n const $x = convertToTensor(x, 'x', 'clipByValue');\n util.assert(\n (clipValueMin <= clipValueMax),\n () => `Error in clip: min (${clipValueMin}) must be ` +\n `less than or equal to max (${clipValueMax}).`);\n\n if (clipValueMin === clipValueMax) {\n return fill($x.shape, clipValueMin, $x.dtype) as T;\n }\n\n const inputs: ClipByValueInputs = {x: $x};\n const attrs: ClipByValueAttrs = {clipValueMin, clipValueMax};\n\n return ENGINE.runKernel(\n ClipByValue, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const clipByValue = /* @__PURE__ */ op({clipByValue_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(3) = |r1, g1, b1|\n * B: shape(2) = |r2, g2|\n * C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @return The concatenated array.\n */\nfunction concat1d_(tensors: Array): Tensor1D {\n return concat(tensors, 0 /* axis */);\n}\n\nexport const concat1d = /* @__PURE__ */ op({concat1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(2, 3) = | r1, g1, b1 |\n * | r2, g2, b2 |\n *\n * B: shape(2, 3) = | r3, g3, b3 |\n * | r4, g4, b4 |\n *\n * C = tf.concat2d([A, B], axis)\n *\n * if axis = 0:\n * C: shape(4, 3) = | r1, g1, b1 |\n * | r2, g2, b2 |\n * | r3, g3, b3 |\n * | r4, g4, b4 |\n *\n * if axis = 1:\n * C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |\n * | r2, g2, b2, r4, g4, b4 |\n *\n *\n * @param tensors A list of `tf.Tensor`s to concatenate.\n * @param axis The axis to concatenate along.\n * @return The concatenated array.\n */\nfunction concat2d_(\n tensors: Array, axis: number): Tensor2D {\n return concat(tensors, axis);\n}\n\nexport const concat2d = /* @__PURE__ */ op({concat2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor3D`s along an axis.\n * See `concat` for details.\n *\n * For example, if:\n * A: shape(2, 1, 3) = | r1, g1, b1 |\n * | r2, g2, b2 |\n *\n * B: shape(2, 1, 3) = | r3, g3, b3 |\n * | r4, g4, b4 |\n *\n * C = tf.concat3d([A, B], axis)\n *\n * if axis = 0:\n * C: shape(4, 1, 3) = | r1, g1, b1 |\n * | r2, g2, b2 |\n * | r3, g3, b3 |\n * | r4, g4, b4 |\n *\n * if axis = 1:\n * C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |\n * | r2, g2, b2, r4, g4, b4 |\n *\n * if axis = 2:\n * C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |\n * | r2, g2, b2, r4, g4, b4 |\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @param axis The axis to concate along.\n * @return The concatenated array.\n */\nfunction concat3d_(\n tensors: Array, axis: number): Tensor3D {\n return concat(tensors, axis);\n}\n\nexport const concat3d = /* @__PURE__ */ op({concat3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor4D`s along an axis.\n * See `concat` for details.\n *\n * @param tensors A list of `tf.Tensor`s to concatenate.\n * @param axis The axis to concate along.\n * @return The concatenated array.\n */\nfunction concat4d_(\n tensors: Array, axis: number): Tensor4D {\n return concat(tensors, axis);\n}\n\nexport const concat4d = /* @__PURE__ */ op({concat4d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2D, Conv2DAttrs, Conv2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 2D convolution over the input x.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2d_(\n x: T|TensorLike, filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in conv2d: filter must be rank 4, but got rank ` +\n `${$filter.rank}.`);\n conv_util.checkPadOnDimRoundingMode('conv2d', pad, dimRoundingMode);\n const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n util.assert(\n inDepth === $filter.shape[2],\n () => `Error in conv2d: depth of input (${inDepth}) must match ` +\n `input depth for filter ${$filter.shape[2]}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n util.assert(\n conv_util.stridesOrDilationsArePositive(dilations),\n () => 'Error in conv2D: Dilated rates should be larger than 0.');\n util.assert(\n conv_util.stridesOrDilationsArePositive(strides),\n () => 'Error in conv2D: Strides should be larger than 0.');\n\n const inputs: Conv2DInputs = {x: x4D, filter: $filter};\n const attrs:\n Conv2DAttrs = {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv2D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const conv2d = /* @__PURE__ */ op({conv2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D, Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 1D convolution over the input x.\n *\n * @param x The input tensor, of rank 3 or rank 2, of shape\n * `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.\n * @param filter The filter, rank 3, of shape\n * `[filterWidth, inDepth, outDepth]`.\n * @param stride The number of entries by which the filter is moved right at\n * each step.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from \"NWC\", \"NCW\". Defaults to \"NWC\",\n * the data is stored in the order of [batch, in_width, in_channels]. Only\n * \"NWC\" is currently supported.\n * @param dilation The dilation rate in which we sample input values in\n * atrous convolution. Defaults to `1`. If it is greater than 1, then\n * stride must be `1`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv1d_(\n x: T|TensorLike, filter: Tensor3D|TensorLike, stride: number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NWC'|'NCW' = 'NWC', dilation = 1,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'conv1d');\n const $filter = convertToTensor(filter, 'filter', 'conv1d');\n\n let x3D = $x as Tensor3D;\n let reshapedTo3D = false;\n if ($x.rank === 2) {\n reshapedTo3D = true;\n x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);\n }\n\n util.assert(\n x3D.rank === 3,\n () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);\n util.assert(\n $filter.rank === 3,\n () => `Error in conv1d: filter must be rank 3, but got rank ` +\n `${$filter.rank}.`);\n conv_util.checkPadOnDimRoundingMode('conv1d', pad, dimRoundingMode);\n util.assert(\n x3D.shape[2] === $filter.shape[1],\n () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +\n `input depth for filter ${$filter.shape[1]}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(stride, dilation),\n () => 'Error in conv1D: Either stride or dilation must be 1. ' +\n `Got stride ${stride} and dilation '${dilation}'`);\n util.assert(\n conv_util.stridesOrDilationsArePositive(dilation),\n () => 'Error in conv1D: Dilated rates should be larger than 0.');\n util.assert(\n conv_util.stridesOrDilationsArePositive(stride),\n () => 'Error in conv1D: Stride should be larger than 0.');\n util.assert(\n dataFormat === 'NWC',\n () => `Error in conv1d: got dataFormat of ${\n dataFormat} but only NWC is currently supported.`);\n\n const filter4D = reshape(\n $filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);\n const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);\n const strides: [number, number] = [1, stride];\n const dilations: [number, number] = [1, dilation];\n\n const conv2dDataFormat = 'NHWC';\n\n const res = conv2d(\n (input4D as Tensor4D), (filter4D as Tensor4D), strides, pad,\n conv2dDataFormat, dilations, dimRoundingMode);\n\n if (reshapedTo3D) {\n return reshape(res, [res.shape[2], res.shape[3]]) as T;\n }\n\n return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]) as T;\n}\n\nexport const conv1d = /* @__PURE__ */ op({conv1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 2D convolution.\n *\n * @param xShape The shape of the input: [batch, height, width, inDepth].\n * If length of 3, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 4 or rank 3 of shape\n * `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction conv2DBackpropInput_(\n xShape: [number, number, number, number]|[number, number, number], dy: T,\n filter: Tensor4D, strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n util.assert(\n xShape.length === dy.rank,\n () => `Length of inShape ` +\n `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n let xShape4D = xShape as [number, number, number, number];\n let dy4D = dy as Tensor4D;\n let reshapedTo4D = false;\n if (dy.rank === 3) {\n reshapedTo4D = true;\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n xShape4D = [1, xShape[0], xShape[1], xShape[2]];\n }\n\n util.assert(\n xShape4D.length === 4,\n () =>\n `Error in conv2dDerInput: inShape must be length 4, but got length ` +\n `${xShape4D.length}.`);\n util.assert(\n dy4D.rank === 4,\n () => `Error in conv2dDerInput: dy must be rank 4, but got ` +\n `rank ${dy4D.rank}`);\n util.assert(\n filter.rank === 4,\n () => `Error in conv2dDerInput: filter must be rank 4, but got ` +\n `rank ${filter.rank}`);\n const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];\n const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n util.assert(\n inDepth === filter.shape[2],\n () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +\n `match input depth for filter ${filter.shape[2]}.`);\n util.assert(\n outDepth === filter.shape[3],\n () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +\n `match output depth for filter ${filter.shape[3]}.`);\n conv_util.checkPadOnDimRoundingMode('conv2dDerInput', pad, dimRoundingMode);\n const inputs: Conv2DBackpropInputInputs = {dy: dy4D, filter};\n const attrs: Conv2DBackpropInputAttrs =\n {strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv2DBackpropInput, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const conv2DBackpropInput = /* @__PURE__ */ op({conv2DBackpropInput_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv2DBackpropInput} from './conv2d_backprop_input';\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 2D convolution of an image, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 4 or rank 3, of shape\n * `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, outDepth, inDepth]`.\n * `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 4 or rank 3:\n * `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.\n * @param strides The strides of the original convolution:\n * `[strideHeight, strideWidth]`.\n * @param pad The type of padding algorithm used in the non-transpose version\n * of the op.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2dTranspose_(\n x: T|TensorLike, filter: Tensor4D|TensorLike,\n outputShape: [number, number, number, number]|[number, number, number],\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'conv2dTranspose');\n const $filter = convertToTensor(filter, 'filter', 'conv2dTranspose');\n\n return conv2DBackpropInput(\n outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);\n}\n\nexport const conv2dTranspose = /* @__PURE__ */ op({conv2dTranspose_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3D, Conv3DAttrs, Conv3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {eitherStridesOrDilationsAreOne, stridesOrDilationsArePositive} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 3D convolution over the input x.\n *\n * @param x The input tensor, of rank 5 or rank 4, of shape\n * `[batch, depth, height, width, channels]`. If rank 4,\n * batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n * `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.\n * inChannels must match between input and filter.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n * \"NDHWC\". Specify the data format of the input and output data. With the\n * default format \"NDHWC\", the data is stored in the order of: [batch,\n * depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationDepth, dilationHeight,\n * dilationWidth]` in which we sample input values across the height\n * and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.\n * If `dilations` is a single number, then\n * `dilationDepth == dilationHeight == dilationWidth`. If it is greater\n * than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3d_(\n x: T|TensorLike, filter: Tensor5D|TensorLike,\n strides: [number, number, number]|number, pad: 'valid'|'same',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC',\n dilations: [number, number, number]|number = [1, 1, 1]): T {\n const $x = convertToTensor(x, 'x', 'conv3d');\n const $filter = convertToTensor(filter, 'filter', 'conv3d');\n\n let x5D = $x as Tensor5D;\n let reshapedTo5D = false;\n\n if ($x.rank === 4) {\n reshapedTo5D = true;\n x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n }\n util.assert(\n x5D.rank === 5,\n () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);\n util.assert(\n $filter.rank === 5,\n () => `Error in conv3d: filter must be rank 5, but got rank ` +\n `${$filter.rank}.`);\n util.assert(\n x5D.shape[4] === $filter.shape[3],\n () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +\n `input depth for filter ${$filter.shape[3]}.`);\n util.assert(\n eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in conv3D: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n util.assert(\n dataFormat === 'NDHWC',\n () => `Error in conv3d: got dataFormat of ${\n dataFormat} but only NDHWC is currently supported.`);\n util.assert(\n stridesOrDilationsArePositive(dilations),\n () => 'Error in conv3D: Dilated rates should be larger than 0.');\n util.assert(\n stridesOrDilationsArePositive(strides),\n () => 'Error in conv3D: Strides should be larger than 0.');\n\n const inputs: Conv3DInputs = {x: x5D, filter: $filter};\n\n const attrs: Conv3DAttrs = {strides, pad, dataFormat, dilations};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv3D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n return res;\n}\n\nexport const conv3d = /* @__PURE__ */ op({conv3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 3D convolution.\n *\n * @param xShape The shape of the input: [batch, depth, height, width,\n * in_channels]. If length of 4, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 5 or rank 4 of shape\n * `[batch, outDepth, outHeight, outWidth, in_channels]`.\n * If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n * `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n */\nfunction conv3DBackpropInput_(\n xShape:\n [number, number, number, number,\n number]|[number, number, number, number],\n dy: T, filter: Tensor5D, strides: [number, number, number]|number,\n pad: 'valid'|'same'): T {\n util.assert(\n xShape.length === dy.rank,\n () => `Length of inShape ` +\n `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n let xShape5D = xShape as [number, number, number, number, number];\n let dy5D = dy as Tensor5D;\n let reshapedTo5D = false;\n if (dy.rank === 4) {\n reshapedTo5D = true;\n dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);\n xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];\n }\n\n const inDepth = xShape5D[4];\n const outDepth = dy5D.shape[4];\n util.assert(\n xShape5D.length === 5,\n () =>\n `Error in conv3dDerInput: inShape must be length 5, but got length ` +\n `${xShape5D.length}.`);\n util.assert(\n dy5D.rank === 5,\n () => `Error in conv3dDerInput: dy must be rank 5, but got ` +\n `rank ${dy5D.rank}`);\n util.assert(\n filter.rank === 5,\n () => `Error in conv3dDerInput: filter must be rank 5, but got ` +\n `rank ${filter.rank}`);\n util.assert(\n inDepth === filter.shape[3],\n () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +\n `match input depth for filter ${filter.shape[3]}.`);\n util.assert(\n outDepth === filter.shape[4],\n () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +\n `match output depth for filter ${filter.shape[4]}.`);\n\n const inputs: Conv3DBackpropInputV2Inputs = {dy: dy5D, filter};\n\n const attrs:\n Conv3DBackpropInputV2Attrs = {pad, strides, inputShape: xShape5D};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Conv3DBackpropInputV2, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n return res;\n}\n\nexport const conv3DBackpropInput = /* @__PURE__ */ op({conv3DBackpropInput_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv3DBackpropInput} from './conv3d_backprop_input';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 3D convolution of a volume, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 5 or rank 4, of shape\n * `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n * `[depth, filterHeight, filterWidth, outDepth, inDepth]`.\n * `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 5 or rank 4:\n * `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is\n * assumed.\n * @param strides The strides of the original convolution:\n * `[strideDepth, strideHeight, strideWidth]`.\n * @param pad The type of padding algorithm used in the non-transpose version\n * of the op.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3dTranspose_(\n x: T|TensorLike, filter: Tensor5D|TensorLike,\n outputShape:\n [number, number, number, number,\n number]|[number, number, number, number],\n strides: [number, number, number]|number, pad: 'valid'|'same'): T {\n const $x = convertToTensor(x, 'x', 'conv3dTranspose');\n const $filter = convertToTensor(filter, 'filter', 'conv3dTranspose');\n\n return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);\n}\n\nexport const conv3dTranspose = /* @__PURE__ */ op({conv3dTranspose_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cos, CosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes cos of the input `tf.Tensor` element-wise: `cos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.cos().print(); // or tf.cos(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cos_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'cos', 'float32');\n\n const inputs: CosInputs = {x: $x};\n\n return ENGINE.runKernel(Cos, inputs as unknown as NamedTensorMap);\n}\nexport const cos = /* @__PURE__ */ op({cos_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cosh, CoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.cosh().print(); // or tf.cosh(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cosh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'cosh', 'float32');\n const inputs: CoshInputs = {x: $x};\n\n return ENGINE.runKernel(Cosh, inputs as unknown as NamedTensorMap);\n}\nexport const cosh = /* @__PURE__ */ op({cosh_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { ENGINE } from '../engine';\nimport { Cumprod, CumprodAttrs, CumprodInputs } from '../kernel_names';\nimport { NamedAttrMap } from '../kernel_registry';\nimport { Tensor } from '../tensor';\nimport { NamedTensorMap } from '../tensor_types';\nimport { convertToTensor } from '../tensor_util_env';\nimport { TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Computes the cumulative product of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumprod().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumprod().print();\n * ```\n *\n * @param x The input tensor to cumulatively multiply.\n * @param axis The axis along which to multiply. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative product. Optional.\n * Defaults to false. If set to true then the product of each tensor entry\n * does not include its own value, but only the values previous to it\n * along the specified axis.\n * @param reverse Whether to multiply in the opposite direction. Optional.\n * Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumprod_(\n x: Tensor | TensorLike,\n axis = 0,\n exclusive = false,\n reverse = false\n): T {\n const $x = convertToTensor(x, 'x', 'cumprod');\n\n const inputs: CumprodInputs = { x: $x };\n const attrs: CumprodAttrs = { axis, exclusive, reverse };\n\n return ENGINE.runKernel(\n Cumprod,\n inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap\n );\n}\n\nexport const cumprod = /* @__PURE__ */ op({ cumprod_ });\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cumsum, CumsumAttrs, CumsumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the cumulative sum of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumsum().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumsum().print();\n * ```\n *\n * @param x The input tensor to be summed.\n * @param axis The axis along which to sum. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative sum. Optional.\n * Defaults to false. If set to true then the sum of each tensor entry\n * does not include its own value, but only the values previous to it\n * along the specified axis.\n * @param reverse Whether to sum in the opposite direction. Optional.\n * Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumsum_(\n x: Tensor|TensorLike, axis = 0, exclusive = false, reverse = false): T {\n const $x = convertToTensor(x, 'x', 'cumsum');\n\n const inputs: CumsumInputs = {x: $x};\n const attrs: CumsumAttrs = {axis, exclusive, reverse};\n\n return ENGINE.runKernel(\n Cumsum, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const cumsum = /* @__PURE__ */ op({cumsum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1 or rank 2.\n * @param weights The weights tensor, must have the same shape as x, or a\n * length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n * @param binaryOutput Optional. Whether the kernel should count the appearance\n * or number of occurrences. Defaults to False.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction denseBincount_(\n x: T|TensorLike, weights: T|TensorLike, size: number,\n binaryOutput = false): T {\n const $x = convertToTensor(x, 'x', 'denseBincount');\n const $weights = convertToTensor(weights, 'weights', 'denseBincount');\n\n util.assert(\n $x.dtype === 'int32',\n () => `Error in denseBincount: input ` +\n `dtype must be int32, but got ${$x.dtype}`);\n util.assert(\n $x.rank <= 2,\n () => `Error in denseBincount: input must be at most rank 2, but got ` +\n `rank ${$x.rank}.`);\n util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n util.assert(\n $weights.size === $x.size || $weights.size === 0,\n () =>\n `Error in denseBincount: weights must have the same shape as x or ` +\n `0-length, but got x shape: ${$x.shape}, weights shape: ` +\n `${$weights.shape}.`);\n\n const inputs: DenseBincountInputs = {x: $x, weights: $weights};\n const attrs: DenseBincountAttrs = {size, binaryOutput};\n\n return ENGINE.runKernel(\n DenseBincount, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const denseBincount = /* @__PURE__ */ op({denseBincount_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Rearranges data from depth into blocks of spatial data. More specifically,\n * this op outputs a copy of the input tensor where values from the `depth`\n * dimension are moved in spatial blocks to the `height` and `width` dimensions.\n * The attr `blockSize` indicates the input block size and how the data is\n * moved.\n *\n * - Chunks of data of size `blockSize * blockSize` from depth are rearranged\n * into non-overlapping blocks of size `blockSize x blockSize`\n *\n * - The width the output tensor is `inputWidth * blockSize`, whereas the\n * height is `inputHeight * blockSize`\n *\n * - The Y, X coordinates within each block of the output image are determined\n * by the high order component of the input channel index\n *\n * - The depth of the input tensor must be divisible by `blockSize *\n * blockSize`\n *\n * The `dataFormat` attr specifies the layout of the input and output tensors\n * with the following options: \"NHWC\": [ `batch, height, width, channels` ]\n * \"NCHW\": [ `batch, channels, height, width` ]\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);\n * const blockSize = 2;\n * const dataFormat = \"NHWC\";\n *\n * tf.depthToSpace(x, blockSize, dataFormat).print();\n * ```\n *\n * @param x The input tensor of rank 4\n * @param blockSIze An `int` that is `>= 2`. The size of the spatial block\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to \"NHWC\"\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction depthToSpace_(\n x: Tensor4D|TensorLike4D, blockSize: number,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC'): Tensor4D {\n const $x = convertToTensor(x, 'x', 'depthToSpace', 'float32') as Tensor4D;\n\n const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];\n const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];\n const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];\n\n util.assert(\n blockSize > 1,\n () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n util.assert(\n inputHeight * blockSize >= 0,\n () => `Negative dimension size caused by overflow when multiplying\n ${inputHeight} and ${blockSize} for depthToSpace with input shape\n ${$x.shape}`);\n\n util.assert(\n inputWidth * blockSize >= 0,\n () => `Negative dimension size caused by overflow when multiplying\n ${inputWidth} and ${blockSize} for depthToSpace with input shape\n ${$x.shape}`);\n\n util.assert(\n (inputDepth % (blockSize * blockSize) === 0),\n () => `Dimension size must be evenly divisible by ${\n blockSize * blockSize} but is ${\n inputDepth} for depthToSpace with input shape ${$x.shape}`);\n\n const inputs: DepthToSpaceInputs = {x: $x};\n const attrs: DepthToSpaceAttrs = {blockSize, dataFormat};\n\n return ENGINE.runKernel(\n DepthToSpace, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const depthToSpace = /* @__PURE__ */ op({depthToSpace_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Depthwise 2D convolution.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n * https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction depthwiseConv2d_(\n x: T|TensorLike, filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n const $filter =\n convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in depthwiseConv2d: input must be rank 4, but got ` +\n `rank ${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +\n `${$filter.rank}.`);\n const inChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n util.assert(\n inChannels === $filter.shape[2],\n () => `Error in depthwiseConv2d: number of input channels ` +\n `(${inChannels}) must match the inChannels dimension in ` +\n `filter ${$filter.shape[2]}.`);\n conv_util.checkPadOnDimRoundingMode('depthwiseConv2d', pad, dimRoundingMode);\n const inputs: DepthwiseConv2dNativeInputs = {x: x4D, filter: $filter};\n const attrs: DepthwiseConv2dNativeAttrs =\n {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n DepthwiseConv2dNative, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const depthwiseConv2d = /* @__PURE__ */ op({depthwiseConv2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Diag, DiagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Returns a diagonal tensor with given diagonal values.\n *\n * Given a diagonal, this operation returns a tensor with the diagonal and\n * everything else padded with zeros.\n *\n * Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor\n * of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * tf.diag(x).print()\n * ```\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [4, 2])\n *\n * tf.diag(x).print()\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction diag_(x: Tensor): Tensor {\n const $x = convertToTensor(x, 'x', 'diag');\n\n const inputs: DiagInputs = {x: $x};\n\n return ENGINE.runKernel(Diag, inputs as unknown as NamedTensorMap);\n}\n\nexport const diag = /* @__PURE__ */ op({diag_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Dilation2D, Dilation2DAttrs, Dilation2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the grayscale dilation over the input `x`.\n *\n * @param x The input tensor, rank 3 or rank 4 of shape\n * `[batch, height, width, depth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter tensor, rank 3, of shape\n * `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n * input tensor: `[strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat Specify the data format of the input and output data.\n * Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`\n * is a single number, then `dilationHeight == dilationWidth`. If it is\n * greater than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction dilation2d_(\n x: T|TensorLike, filter: Tensor3D|TensorLike,\n strides: [number, number]|number, pad: 'valid'|'same',\n dilations: [number, number]|number = [1, 1],\n dataFormat: 'NHWC' = 'NHWC'): T {\n const $x = convertToTensor(x, 'x', 'dilation2d');\n const $filter = convertToTensor(filter, 'filter', 'dilation2d');\n\n util.assert(\n $x.rank === 3 || $x.rank === 4,\n () => `Error in dilation2d: input must be rank 3 or 4, but got rank ` +\n `${$x.rank}.`);\n util.assert(\n $filter.rank === 3,\n () => `Error in dilation2d: filter must be rank 3, but got rank ` +\n `${$filter.rank}.`);\n util.assert(\n dataFormat === 'NHWC',\n () => `Error in dilation2d: Only NHWC is currently supported, ` +\n `but got dataFormat of ${dataFormat}`);\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n reshapedTo4D = true;\n }\n\n util.assert(\n x4D.shape[3] === $filter.shape[2],\n () => `Error in dilation2d: input and filter must have the same depth: ${\n x4D.shape[3]} vs ${$filter.shape[2]}`);\n\n const inputs: Dilation2DInputs = {x: x4D, filter: $filter};\n const attrs: Dilation2DAttrs = {strides, pad, dilations};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Dilation2D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n\n return res;\n}\n\nexport const dilation2d = /* @__PURE__ */ op({dilation2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'equal', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'equal', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: EqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Equal, inputs as unknown as NamedTensorMap);\n}\n\nexport const equal = /* @__PURE__ */ op({equal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Select, SelectInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {broadcastTo} from './broadcast_to';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the elements, either `a` or `b` depending on the `condition`.\n *\n * If the condition is true, select from `a`, otherwise select from `b`.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const a = tf.tensor1d([1 , 2, 3]);\n * const b = tf.tensor1d([-1, -2, -3]);\n *\n * a.where(cond, b).print();\n * ```\n *\n * @param condition The input condition. Must be of dtype bool.\n * @param a If `condition` is rank 1, `a` may have a higher rank but\n * its first dimension must match the size of `condition`.\n * @param b A tensor with the same dtype as `a` and with shape that is\n * compatible with `a`.\n * @return A tensor with same dtype as `a` and `b`, and shape that is\n * broadcastable from `a` and `b`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction where_(\n condition: Tensor|TensorLike, a: T|TensorLike, b: T|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'where');\n const $b = convertToTensor(b, 'b', 'where');\n const $condition = convertToTensor(condition, 'condition', 'where', 'bool');\n // TODO: move this logic to forward function when the broadcastTo op is\n // implemented in WASM.\n // Find the broadcastable shape for $condition, $a, and $b.\n const broadcastShape = assertAndGetBroadcastShape(\n assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);\n const $broadcastedCondition = broadcastTo($condition, broadcastShape);\n const $broadcastedA = broadcastTo($a, broadcastShape);\n const $broadcastedB = broadcastTo($b, broadcastShape);\n\n const inputs: SelectInputs = {\n condition: $broadcastedCondition,\n t: $broadcastedA,\n e: $broadcastedB\n };\n return ENGINE.runKernel(Select, inputs as unknown as NamedTensorMap);\n}\n\nexport const where = /* @__PURE__ */ op({where_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n // TODO: Make this into its own kernel.\n let $a = convertToTensor(a, 'a', 'div');\n let $b = convertToTensor(b, 'b', 'div');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const divResult = div($a, $b);\n const zeros = zerosLike(divResult);\n const bEqualsZero = equal($b, zeros);\n return where(bEqualsZero, zeros, divResult) as T;\n}\n\nexport const divNoNan = /* @__PURE__ */ op({divNoNan_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor,} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the dot product of two matrices and/or vectors, `t1` and `t2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor2d([[1, 2], [3, 4]]);\n * const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n *\n * a.dot(b).print(); // or tf.dot(a, b)\n * b.dot(a).print();\n * b.dot(c).print();\n * ```\n * @param t1 The first tensor in the dot operation.\n * @param t2 The second tensor in the dot operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction dot_(t1: Tensor|TensorLike, t2: Tensor|TensorLike): Tensor {\n const $t1 = convertToTensor(t1, 't1', 'dot');\n const $t2 = convertToTensor(t2, 't2', 'dot');\n\n util.assert(\n ($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2),\n () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +\n `${$t1.rank} and ${$t2.rank}.`);\n\n const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);\n const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);\n\n util.assert(\n t1Inner === t2Inner,\n () => `Error in dot: inner dimensions of inputs must match, but got ` +\n `${t1Inner} and ${t2Inner}.`);\n\n if ($t1.rank === 1 && $t2.rank === 1) {\n const t12D = reshape($t1, [1, -1]);\n const t22D = reshape($t2, [-1, 1]);\n const t1t2 = matMul(t12D, t22D);\n return reshape(t1t2, []);\n } else if ($t1.rank === 1 && $t2.rank === 2) {\n const t12D = reshape($t1, [1, -1]);\n const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n const t1t2 = matMul(t12D, t22D);\n return reshape(t1t2, [t1t2.size]);\n } else if ($t1.rank === 2 && $t2.rank === 1) {\n const t22D = reshape($t2, [-1, 1]);\n const t1t2 = matMul($t1, t22D);\n return reshape(t1t2, [t1t2.size]);\n } else {\n const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n const t1t2 = matMul($t1, t22D);\n return t1t2;\n }\n}\n\nexport const dot = /* @__PURE__ */ op({dot_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Einsum, EinsumAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Tensor contraction over specified indices and outer product.\n *\n * `einsum` allows defining Tensors by defining their element-wise computation.\n * This computation is based on\n * [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).\n *\n * Some special cases include:\n *\n * Matrix multiplication:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('ij,jk->ik', x, y).print();\n * ```\n *\n * Dot product:\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n * const y = tf.tensor1d([0, 1, 2]);\n * x.print();\n * y.print();\n * tf.einsum('i,i->', x, y).print();\n * ```\n *\n * Batch dot product:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('bi,bi->b', x, y).print();\n * ```\n *\n * Outer prouduct:\n * ```js\n * const x = tf.tensor1d([1, 3, 5]);\n * const y = tf.tensor1d([2, 4, 6]);\n * x.print();\n * y.print();\n * tf.einsum('i,j->ij', x, y).print();\n * ```\n *\n * Matrix transpose:\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * x.print();\n * tf.einsum('ij->ji', x).print();\n * ```\n *\n * Batch matrix transpose:\n * ```js\n * const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);\n * x.print();\n * tf.einsum('bij->bji', x).print();\n * ```\n *\n * Limitations:\n *\n * This implementation of einsum has the following limitations:\n *\n * - Does not support >2 input tensors.\n * - Does not support duplicate axes for any given input tensor. E.g., equation\n * 'ii->' is not supported.\n * - The `...` notation is not supported.\n *\n * @param equation a string describing the contraction, in the same format as\n * [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).\n * @param tensors the input(s) to contract (each one a Tensor), whose shapes\n * should be consistent with equation.\n * @returns The output tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Matrices'}\n */\nexport function einsum_(equation: string, ...tensors: Tensor[]): Tensor {\n const $tensors =\n tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));\n const attrs: EinsumAttrs = {equation};\n return ENGINE.runKernel(\n Einsum, $tensors as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const einsum = /* @__PURE__ */ op({einsum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Elu, EluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 1, -3, 2]);\n *\n * x.elu().print(); // or tf.elu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction elu_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'elu', 'float32');\n\n const inputs: EluInputs = {x: $x};\n\n return ENGINE.runKernel(Elu, inputs as unknown as NamedTensorMap);\n}\n\nexport const elu = /* @__PURE__ */ op({elu_});\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap} from '../types';\nimport {arraysEqualWithNull} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Checks the input tensor mathes the given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * The method supports the null value in tensor. It will still check the shapes,\n * and null is a placeholder.\n *\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const y = tf.tensor1d([1, null, 3, 4]);\n * const z = tf.tensor2d([1, 2, 3, 4], [2,2]);\n * tf.ensureShape(x, [4]).print();\n * tf.ensureShape(y, [4]).print();\n * tf.ensureShape(z, [null, 2]).print();\n * ```\n *\n * @param x The input tensor to be ensured.\n * @param shape A TensorShape representing the shape of this tensor, an array\n * or null.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction ensureShape_(x: Tensor, shape: ShapeMap[R]): Tensor {\n const $x = convertToTensor(x, 'x', 'ensureShape', 'string_or_numeric');\n if (!arraysEqualWithNull($x.shape, shape)) {\n throw new Error(`EnsureShape: Shape of tensor ${\n $x.shape} is not compatible with expected shape ${shape}`);\n }\n\n return x;\n}\nexport const ensureShape = /* @__PURE__ */ op({ensureShape_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Erf, ErfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes Gauss error function of the input `tf.Tensor` element-wise:\n * `erf(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.erf().print(); // or tf.erf(x);\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction erf_(x: T|TensorLike): T {\n let $x = convertToTensor(x, 'x', 'erf');\n util.assert(\n $x.dtype === 'int32' || $x.dtype === 'float32',\n () => 'Input dtype must be `int32` or `float32`.');\n\n if ($x.dtype === 'int32') {\n $x = cast($x, 'float32');\n }\n\n const inputs: ErfInputs = {x: $x};\n return ENGINE.runKernel(Erf, inputs as unknown as NamedTensorMap);\n}\nexport const erf = /* @__PURE__ */ op({erf_});\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\n/**\n * Returns true if the axis specifies the inner most dimensions of the\n * array.\n */\nexport function axesAreInnerMostDims(axes: number[], rank: number): boolean {\n for (let i = 0; i < axes.length; ++i) {\n if (axes[axes.length - i - 1] !== rank - 1 - i) {\n return false;\n }\n }\n return true;\n}\n\nexport function combineLocations(\n outputLoc: number[], reduceLoc: number[], axes: number[]): number[] {\n const rank = outputLoc.length + reduceLoc.length;\n const loc = [];\n let outIdx = 0;\n let reduceIdx = 0;\n   for (let dim = 0; dim < rank; dim++) {\n if (axes.indexOf(dim) === -1) {\n loc.push(outputLoc[outIdx++]);\n } else {\n loc.push(reduceLoc[reduceIdx++]);\n }\n }\n return loc;\n}\n\nexport function computeOutAndReduceShapes(\n aShape: number[], axes: number[]): [number[], number[]] {\n const outShape = [];\n const rank = aShape.length;\n for (let dim = 0; dim < rank; dim++) {\n if (axes.indexOf(dim) === -1) {\n outShape.push(aShape[dim]);\n }\n }\n const reduceShape = axes.map(dim => aShape[dim]);\n return [outShape, reduceShape];\n}\n\nexport function expandShapeToKeepDim(\n shape: number[], axes: number[]): number[] {\n const reduceSubShape = axes.map(x => 1);\n return combineLocations(shape, reduceSubShape, axes);\n}\n\nexport function assertAxesAreInnerMostDims(\n msg: string, axes: number[], rank: number): void {\n util.assert(\n axesAreInnerMostDims(axes, rank),\n () => `${msg} supports only inner-most axes for now. ` +\n `Got axes ${axes} and rank-${rank} input.`);\n}\n\n/**\n * Returns the axes permutation to be used with `tf.transpose`, if such\n * permutation is necessary. Otherwise it returns null. This method is used by\n * operations that operate only on inner-most axes.\n */\nexport function getAxesPermutation(axes: number[], rank: number): number[]|\n null {\n if (axesAreInnerMostDims(axes, rank)) {\n return null;\n }\n const result: number[] = [];\n for (let i = 0; i < rank; ++i) {\n if (axes.indexOf(i) === -1) {\n result.push(i);\n }\n }\n axes.forEach(axis => result.push(axis));\n return result;\n}\n\n/** Returns the axes permutation that undoes the original permutation. */\nexport function getUndoAxesPermutation(axes: number[]): number[] {\n return axes.map((axis, i) => [i, axis])\n .sort((a, b) => a[1] - b[1])\n .map(x => x[0]);\n}\n\nexport function getInnerMostAxes(numAxes: number, rank: number): number[] {\n const res: number[] = [];\n for (let i = rank - numAxes; i < rank; ++i) {\n res.push(i);\n }\n return res;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Max, MaxAttrs, MaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the maximum of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.max().print(); // or tf.max(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.max(axis).print(); // or tf.max(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction max_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'max');\n\n const inputs: MaxInputs = {x: $x};\n const attrs: MaxAttrs = {reductionIndices: axis, keepDims};\n\n return ENGINE.runKernel(\n Max, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const max = /* @__PURE__ */ op({max_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Min, MinAttrs, MinInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the minimum value from the input.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the array is reduced by 1 for each entry in `axes`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axes` has no entries, all dimensions are reduced, and an array with a\n * single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.min().print(); // or tf.min(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.min(axis).print(); // or tf.min(x, axis)\n * ```\n *\n * @param x The input Tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction min_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'min');\n\n const inputs: MinInputs = {x: $x};\n const attrs: MinAttrs = {axis, keepDims};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n Min, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n}\n\nexport const min = /* @__PURE__ */ op({min_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n let $x = convertToTensor(x, 'x', 'sum');\n if ($x.dtype === 'bool') {\n $x = cast($x, 'int32');\n }\n\n const inputs: SumInputs = {x: $x};\n const attrs: SumAttrs = {axis, keepDims};\n\n return ENGINE.runKernel(\n Sum, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const sum = /* @__PURE__ */ op({sum_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {abs} from './abs';\nimport * as axis_util from './axis_util';\nimport {max} from './max';\nimport {min} from './min';\nimport {op} from './operation';\nimport {pow} from './pow';\nimport {reshape} from './reshape';\nimport {scalar} from './scalar';\nimport {sqrt} from './sqrt';\nimport {square} from './square';\nimport {sum} from './sum';\n\n/**\n * Computes the norm of scalar, vectors, and matrices.\n * This function can compute several different vector norms (the 1-norm, the\n * Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)\n * and matrix norms (Frobenius, 1-norm, and inf-norm).\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.norm().print(); // or tf.norm(x)\n * ```\n *\n * @param x The input array.\n * @param ord Optional. Order of the norm. Supported norm types are\n * following:\n *\n * | ord | norm for matrices | norm for vectors\n * |------------|---------------------------|---------------------\n * |'euclidean' |Frobenius norm |2-norm\n * |'fro' |Frobenius norm\t |\n * |Infinity |max(sum(abs(x), axis=1)) |max(abs(x))\n * |-Infinity |min(sum(abs(x), axis=1)) |min(abs(x))\n * |1 |max(sum(abs(x), axis=0)) |sum(abs(x))\n * |2 | |sum(abs(x)^2)^(1/2)\n *\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. norm(x, ord) is equivalent\n * to norm(x.reshape([-1]), ord). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction norm_(\n x: Tensor|TensorLike, ord: number|'euclidean'|'fro' = 'euclidean',\n axis: number|number[] = null, keepDims = false): Tensor {\n x = convertToTensor(x, 'x', 'norm');\n\n const norm = normImpl(x, ord, axis);\n let keepDimsShape = norm.shape;\n if (keepDims) {\n const axes = parseAxisParam(axis, x.shape);\n keepDimsShape = axis_util.expandShapeToKeepDim(norm.shape, axes);\n }\n return reshape(norm, keepDimsShape);\n}\n\nfunction normImpl(\n x: Tensor, p: number|string, axis: number|number[] = null): Tensor {\n if (x.rank === 0) {\n return abs(x);\n }\n\n // consider vector when no axis is specified\n if (x.rank !== 1 && axis === null) {\n return normImpl(reshape(x, [-1]), p, axis);\n }\n\n // vector\n if (x.rank === 1 || typeof axis === 'number' ||\n Array.isArray(axis) && axis.length === 1) {\n if (p === 1) {\n return sum(abs(x), axis);\n }\n if (p === Infinity) {\n return max(abs(x), axis);\n }\n if (p === -Infinity) {\n return min(abs(x), axis);\n }\n if (p === 'euclidean' || p === 2) {\n // norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2\n return sqrt(sum(pow(abs(x), scalar(2, 'int32')), axis));\n }\n\n throw new Error(`Error in norm: invalid ord value: ${p}`);\n }\n\n // matrix (assumption axis[0] < axis[1])\n if (Array.isArray(axis) && axis.length === 2) {\n if (p === 1) {\n return max(sum(abs(x), axis[0]), axis[1] - 1);\n }\n if (p === Infinity) {\n return max(sum(abs(x), axis[1]), axis[0]);\n }\n if (p === -Infinity) {\n return min(sum(abs(x), axis[1]), axis[0]);\n }\n if (p === 'fro' || p === 'euclidean') {\n // norm(x) = sqrt(sum(pow(x, 2)))\n return sqrt(sum(square(x), axis));\n }\n\n throw new Error(`Error in norm: invalid ord value: ${p}`);\n }\n\n throw new Error(`Error in norm: invalid axis: ${axis}`);\n}\n\nexport const norm = /* @__PURE__ */ op({norm_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {norm} from './norm';\nimport {op} from './operation';\n\n/**\n * Computes the Euclidean norm of scalar, vectors, and matrices.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.euclideanNorm().print(); // or tf.euclideanNorm(x)\n * ```\n *\n * @param x The input array.\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. euclideanNorm(x) is equivalent\n * to euclideanNorm(x.reshape([-1])). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction euclideanNorm_(\n x: Tensor|TensorLike, axis: number|number[] = null,\n keepDims = false): Tensor {\n return norm(x, 'euclidean', axis, keepDims);\n}\n\nexport const euclideanNorm = /* @__PURE__ */ op({euclideanNorm_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Exp, ExpInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.exp().print(); // or tf.exp(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction exp_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'exp');\n\n const inputs: ExpInputs = {x: $x};\n return ENGINE.runKernel(Exp, inputs as unknown as NamedTensorMap);\n}\nexport const exp = /* @__PURE__ */ op({exp_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Returns a `tf.Tensor` that has expanded rank, by inserting a dimension\n * into the tensor's shape.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const axis = 1;\n * x.expandDims(axis).print();\n * ```\n *\n * @param x The input tensor whose dimensions are to be expanded.\n * @param axis The dimension index at which to insert shape of `1`. Defaults\n * to 0 (the first dimension).\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction expandDims_(x: Tensor|TensorLike, axis = 0): T {\n const $x = convertToTensor(x, 'x', 'expandDims', 'string_or_numeric');\n\n util.assert(axis <= $x.rank, () => 'Axis must be <= rank of the tensor');\n\n const inputs: ExpandDimsInputs = {input: $x};\n const attrs: ExpandDimsAttrs = {dim: axis};\n\n return ENGINE.runKernel(\n ExpandDims, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const expandDims = /* @__PURE__ */ op({expandDims_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Expm1, Expm1Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` minus one element-wise.\n * `e ^ x - 1`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.expm1().print(); // or tf.expm1(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction expm1_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'expm1');\n\n const inputs: Expm1Inputs = {x: $x};\n return ENGINE.runKernel(Expm1, inputs as unknown as NamedTensorMap);\n}\nexport const expm1 = /* @__PURE__ */ op({expm1_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Construct a tensor by repeating it the number of times given by reps.\n *\n * This operation creates a new tensor by replicating `input` `reps`\n * times. The output tensor's `i`th dimension has `input.shape[i] *\n * reps[i]` elements, and the values of `input` are replicated\n * `reps[i]` times along the `i`th dimension. For example, tiling\n * `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n *\n * a.tile([2]).print(); // or tf.tile(a, [2])\n * ```\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.tile([1, 2]).print(); // or tf.tile(a, [1,2])\n * ```\n * @param x The tensor to tile.\n * @param reps Determines the number of replications per dimension.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction tile_(x: T|TensorLike, reps: number[]): T {\n const $x = convertToTensor(x, 'x', 'tile', 'string_or_numeric');\n util.assert(\n $x.rank === reps.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of reps ${reps}.`);\n\n const inputs: TileInputs = {x: $x};\n const attrs: TileAttrs = {reps};\n\n return ENGINE.runKernel(\n Tile, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const tile = /* @__PURE__ */ op({tile_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {DataType} from '../types';\n\nimport {buffer} from './buffer';\nimport {expandDims} from './expand_dims';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {tile} from './tile';\n\n/**\n * Create an identity matrix.\n *\n * @param numRows Number of rows.\n * @param numColumns Number of columns. Defaults to `numRows`.\n * @param batchShape If provided, will add the batch shape to the beginning\n * of the shape of the returned `tf.Tensor` by repeating the identity\n * matrix.\n * @param dtype Data type.\n * @returns Identity matrix of the specified size and data type, possibly\n * with batch repetition if `batchShape` is specified.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction eye_(\n numRows: number, numColumns?: number,\n batchShape?:\n [\n number\n ]|[number,\n number]|[number, number, number]|[number, number, number, number],\n dtype: DataType = 'float32'): Tensor2D {\n if (numColumns == null) {\n numColumns = numRows;\n }\n const buff = buffer([numRows, numColumns], dtype);\n const n = numRows <= numColumns ? numRows : numColumns;\n for (let i = 0; i < n; ++i) {\n buff.set(1, i, i);\n }\n const out: Tensor2D = reshape(buff.toTensor(), [numRows, numColumns]);\n if (batchShape == null) {\n return out;\n } else {\n if (batchShape.length === 1) {\n return tile(expandDims(out, 0), [batchShape[0], 1, 1]) as Tensor2D;\n } else if (batchShape.length === 2) {\n // tslint:disable-next-line:no-unnecessary-type-assertion\n return tile(\n expandDims(expandDims(out, 0), 0),\n [batchShape[0], batchShape[1], 1, 1]) as Tensor2D;\n } else if (batchShape.length === 3) {\n // tslint:disable-next-line:no-unnecessary-type-assertion\n return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [\n batchShape[0], batchShape[1], batchShape[2], 1, 1\n ]) as Tensor2D;\n } else {\n throw new Error(\n `eye() currently supports only 1D and 2D ` +\n // tslint:disable-next-line:no-any\n `batchShapes, but received ${(batchShape as any).length}D.`);\n }\n }\n}\n\nexport const eye = /* @__PURE__ */ op({eye_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Floor, FloorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes floor of input `tf.Tensor` element-wise: `floor(x)`.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.floor().print(); // or tf.floor(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction floor_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'floor', 'float32');\n\n const inputs: FloorInputs = {x: $x};\n return ENGINE.runKernel(Floor, inputs as unknown as NamedTensorMap);\n}\nexport const floor = /* @__PURE__ */ op({floor_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {GatherV2, GatherV2Attrs, GatherV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Gather slices from tensor `x`'s axis `axis` according to `indices`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const indices = tf.tensor1d([1, 3, 3], 'int32');\n *\n * x.gather(indices).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const indices = tf.tensor1d([1, 1, 0], 'int32');\n *\n * x.gather(indices).print();\n * ```\n * @param x The input tensor whose slices are to be gathered.\n * @param indices The indices of the values to extract.\n * @param axis The axis over which to select values. Defaults to 0.\n * @param batchDims Optional. The number of batch dimensions. It must be less\n * than or equal to rank(indices). Defaults to 0.\n * The output tensor will have shape of\n * `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction gather_(\n x: T|TensorLike, indices: Tensor|TensorLike, axis = 0, batchDims = 0): T {\n const $x = convertToTensor(x, 'x', 'gather');\n const $indices = convertToTensor(indices, 'indices', 'gather', 'int32');\n\n const inputs: GatherV2Inputs = {x: $x, indices: $indices};\n const attrs: GatherV2Attrs = {axis, batchDims};\n\n return ENGINE.runKernel(\n GatherV2, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const gather = /* @__PURE__ */ op({gather_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Greater, GreaterInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a > b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greater(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greater_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'greater', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'greater', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: GreaterInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Greater, inputs as unknown as NamedTensorMap);\n}\n\nexport const greater = /* @__PURE__ */ op({greater_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {GreaterEqual, GreaterEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a >= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greaterEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greaterEqual_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'greaterEqual', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'greaterEqual', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: GreaterEqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(GreaterEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const greaterEqual = /* @__PURE__ */ op({greaterEqual_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'isFinite');\n\n const inputs: IsFiniteInputs = {x: $x};\n\n return ENGINE.runKernel(IsFinite, inputs as unknown as NamedTensorMap);\n}\nexport const isFinite = /* @__PURE__ */ op({isFinite_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsInf, IsInfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are Infinity or -Infinity.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isInf().print(); // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isInf_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'isInf');\n\n const inputs: IsInfInputs = {x: $x};\n\n return ENGINE.runKernel(IsInf, inputs as unknown as NamedTensorMap);\n}\nexport const isInf = /* @__PURE__ */ op({isInf_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsNan, IsNanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are NaN.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isNaN().print(); // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isNaN_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'isNaN');\n const inputs: IsNanInputs = {x: $x};\n\n return ENGINE.runKernel(IsNan, inputs as unknown as NamedTensorMap);\n}\nexport const isNaN = /* @__PURE__ */ op({isNaN_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LeakyRelu, LeakyReluAttrs, LeakyReluInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise.\n *\n * See\n * [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](\n * http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.leakyRelu(0.1).print(); // or tf.leakyRelu(x, 0.1)\n * ```\n * @param x The input tensor.\n * @param alpha The scaling factor for negative values, defaults to 0.2.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction leakyRelu_(x: T|TensorLike, alpha = 0.2): T {\n const $x = convertToTensor(x, 'x', 'leakyRelu');\n\n const inputs: LeakyReluInputs = {x: $x};\n const attrs: LeakyReluAttrs = {alpha};\n\n return ENGINE.runKernel(\n LeakyRelu, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const leakyRelu = /* @__PURE__ */ op({leakyRelu_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Less, LessInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a < b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.less(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction less_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'less', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'less', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LessInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Less, inputs as unknown as NamedTensorMap);\n}\n\nexport const less = /* @__PURE__ */ op({less_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LessEqual, LessEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a <= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.lessEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction lessEqual_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'lessEqual', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'lessEqual', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LessEqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(LessEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const lessEqual = /* @__PURE__ */ op({lessEqual_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LinSpace, LinSpaceAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Return an evenly spaced sequence of numbers over the given interval.\n *\n * ```js\n * tf.linspace(0, 9, 10).print();\n * ```\n * @param start The start value of the sequence.\n * @param stop The end value of the sequence.\n * @param num The number of values to generate.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function linspace(start: number, stop: number, num: number): Tensor1D {\n if (num <= 0) {\n throw new Error('The number of values should be positive.');\n }\n\n const attrs: LinSpaceAttrs = {start, stop, num};\n return ENGINE.runKernel(LinSpace, {}, attrs as unknown as NamedAttrMap);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LRN, LRNAttrs, LRNInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Normalizes the activation of a local neighborhood across or within\n * channels.\n *\n * @param x The input tensor. The 4-D input tensor is treated as a 3-D array\n * of 1D vectors (along the last dimension), and each vector is\n * normalized independently.\n * @param depthRadius The number of adjacent channels in the 1D normalization\n * window.\n * @param bias A constant bias term for the basis.\n * @param alpha A scale factor, usually positive.\n * @param beta An exponent.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction localResponseNormalization_(\n x: T|TensorLike, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5): T {\n const $x = convertToTensor(x, 'x', 'localResponseNormalization');\n util.assert(\n $x.rank === 4 || $x.rank === 3,\n () => `Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${$x.rank}.`);\n util.assert(\n util.isInt(depthRadius),\n () => `Error in localResponseNormalization: depthRadius must be an ` +\n `integer but got depthRadius ${depthRadius}.`);\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n const inputs: LRNInputs = {x: x4D};\n\n const attrs: LRNAttrs = {depthRadius, bias, alpha, beta};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n LRN, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n } else {\n return res;\n }\n}\n\nexport const localResponseNormalization = /* @__PURE__ */ op({localResponseNormalization_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log, LogInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E]);\n *\n * x.log().print(); // or tf.log(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'log', 'float32');\n\n const inputs: LogInputs = {x: $x};\n return ENGINE.runKernel(Log, inputs as unknown as NamedTensorMap);\n}\nexport const log = /* @__PURE__ */ op({log_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log1p, Log1pInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` plus one\n * element-wise: `ln(1 + x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E - 1]);\n *\n * x.log1p().print(); // or tf.log1p(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log1p_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'log1p');\n\n const inputs: Log1pInputs = {x: $x};\n return ENGINE.runKernel(Log1p, inputs as unknown as NamedTensorMap);\n}\nexport const log1p = /* @__PURE__ */ op({log1p_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'softplus');\n\n const inputs: SoftplusInputs = {x: $x};\n return ENGINE.runKernel(Softplus, inputs as unknown as NamedTensorMap);\n}\nexport const softplus = /* @__PURE__ */ op({softplus_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {customGrad} from '../gradients';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {mul} from './mul';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {softplus} from './softplus';\n\n/**\n * Computes log sigmoid of the input `tf.Tensor` element-wise:\n * `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.logSigmoid().print(); // or tf.logSigmoid(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction logSigmoid_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'logSigmoid');\n\n // Use a custom gradient to maintain previous implementation.\n // There is no LogSigmoid kernel in TF so we can't use engine.runKernel\n // directly\n const customOp = customGrad((x: Tensor) => {\n // TODO(yassogba) we can remove the chained softplus call here only\n // after backends have modualrized softplus at which point we can call\n // engine runKernel(..., Sotfplus, ...) directly.\n const value = neg(softplus(neg(x)));\n\n const gradFunc = (dy: T) => {\n const derX = mul(dy, sigmoid(neg(x)));\n return derX;\n };\n return {value, gradFunc};\n });\n\n return customOp($x) as T;\n}\nexport const logSigmoid = /* @__PURE__ */ op({logSigmoid_});\n","/**\n * @license\n * Copyright 2020 Google 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_(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 = (backend, save) => {\n // const keepDims = true;\n // const xMax = max(logits, axis, true);\n // const shifted = sub(logits, xMax);\n // const value =\n // sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,\n // keepDims)));\n // save([value]);\n // return value;\n // };\n\n // Use a custom gradient for numerical stability.\n const customOp = customGrad((logits: Tensor, save: GradSaveFunc) => {\n const keepDims = true;\n const xMax = max(logits, axis, true);\n const shifted = sub(logits, xMax);\n const value =\n sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis, keepDims)));\n save([value]);\n\n const gradFunc = (dy: Tensor, saved: Tensor[]) => {\n const [value] = saved;\n const keepDims = true;\n const softmax = exp(value);\n return sub(dy, mul(sum(dy, axis, keepDims), softmax));\n };\n return {value, gradFunc};\n });\n\n return customOp($logits) as T;\n\n // TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.\n // const inputs: LogSoftmaxInputs = {logits: $logits};\n // const attrs: LogSoftmaxAttrs = {axis};\n // return ENGINE.runKernel(\n // LogSoftmax, inputs as unknown as NamedTensorMap,\n // attrs as unknown as NamedAttrMap);\n}\n\nexport const logSoftmax = /* @__PURE__ */ op({logSoftmax_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {add} from './add';\nimport {expandShapeToKeepDim} from './axis_util';\nimport {exp} from './exp';\nimport {log} from './log';\nimport {max} from './max';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {sub} from './sub';\nimport {sum} from './sum';\n\n/**\n * Computes the log(sum(exp(elements across the reduction dimensions))).\n *\n * Reduces the input along the dimensions given in `axis`. Unless `keepDims`\n * is true, the rank of the array is reduced by 1 for each entry in `axis`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axis` has no entries, all dimensions are reduced, and an array with a\n * single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.logSumExp().print(); // or tf.logSumExp(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.logSumExp(axis).print(); // or tf.logSumExp(a, axis)\n * ```\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. If null (the default),\n * reduces all dimensions.\n * @param keepDims If true, retains reduced dimensions with length\n * of 1. Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction logSumExp_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'logSumExp');\n\n const axes = parseAxisParam(axis, $x.shape);\n const xMax = max($x, axes, true /* keepDims */);\n const a = sub($x, xMax);\n const b = exp(a);\n const c = sum(b, axes);\n const d = log(c);\n const res = add(reshape(xMax, d.shape), d);\n\n if (keepDims) {\n const newShape = expandShapeToKeepDim(res.shape, axes);\n return reshape(res, newShape) as T;\n }\n return res as T;\n}\n\nexport const logSumExp = /* @__PURE__ */ op({logSumExp_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LogicalAnd, LogicalAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a AND b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalAnd(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalAnd_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'logicalAnd', 'bool');\n const $b = convertToTensor(b, 'b', 'logicalAnd', 'bool');\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LogicalAndInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(LogicalAnd, inputs as unknown as NamedTensorMap);\n}\n\nexport const logicalAnd = /* @__PURE__ */ op({logicalAnd_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalNot, LogicalNotInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `NOT x` element-wise.\n *\n * ```js\n * const a = tf.tensor1d([false, true], 'bool');\n *\n * a.logicalNot().print();\n * ```\n *\n * @param x The input tensor. Must be of dtype 'bool'.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalNot_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'logicalNot', 'bool');\n const inputs: LogicalNotInputs = {x: $x};\n return ENGINE.runKernel(LogicalNot, inputs as unknown as NamedTensorMap);\n}\n\nexport const logicalNot = /* @__PURE__ */ op({logicalNot_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalOr, LogicalOrInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a OR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalOr(b).print();\n * ```\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalOr_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'logicalOr', 'bool');\n const $b = convertToTensor(b, 'b', 'logicalOr', 'bool');\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: LogicalOrInputs = {a: $a, b: $b};\n return ENGINE.runKernel(LogicalOr, inputs as unknown as NamedTensorMap);\n}\nexport const logicalOr = /* @__PURE__ */ op({logicalOr_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {logicalAnd} from './logical_and';\nimport {logicalNot} from './logical_not';\nimport {logicalOr} from './logical_or';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a XOR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalXor(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalXor_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n const $a = convertToTensor(a, 'a', 'logicalXor', 'bool');\n const $b = convertToTensor(b, 'b', 'logicalXor', 'bool');\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n // x ^ y = (x | y) & ~(x & y)\n return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));\n}\n\nexport const logicalXor = /* @__PURE__ */ op({logicalXor_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SearchSorted, SearchSortedAttrs, SearchSortedInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nconst INT32_MAX = 2147483648;\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The side argument controls which index is returned if a value lands exactly\n * on an edge.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'sortedSequence' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.searchSorted(edges, values, 'left');\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.searchSorted(seq, values, 'left');\n * result2.print(); // [0, 2, 3]\n * const result3 = tf.searchSorted(seq, values, 'right');\n * result3.print(); // [1, 2, 5]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n * [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n * [0.1, 6.6, 4.5, ]]);\n * const result4 = tf.searchSorted(sortedSequence, values, 'left');\n * result4.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @param side: 'left'|'right'. Defaults to 'left'. 'left' corresponds to lower\n * bound and 'right' to upper bound.\n * @return An N-D int32 tensor the size of values containing the result of\n * applying either lower bound or upper bound (depending on side) to each\n * value. The result is not a global index to the entire Tensor, but the\n * index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction searchSorted_(\n sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike,\n side: 'left'|'right' = 'left'): Tensor {\n const $sortedSequence =\n convertToTensor(sortedSequence, 'sortedSequence', 'searchSorted');\n const $values = convertToTensor(values, 'values', 'searchSorted');\n\n const sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];\n const valuesSize = $values.shape[$values.shape.length - 1];\n const $sortedSequence2D = reshape($sortedSequence, [-1, sequenceSize]);\n const $values2D = reshape($values, [-1, valuesSize]);\n\n if ($sortedSequence2D.rank < 2) {\n throw new Error(`Sorted input argument must be at least 2-dimensional`);\n }\n if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) {\n throw new Error(\n `Leading dimension of 'sortedSequence' and 'values' must match.`);\n }\n if (sizeFromShape($values2D.shape) >= INT32_MAX) {\n throw new Error(`values tensor size must less than ${INT32_MAX}`);\n }\n if ($sortedSequence2D.shape[1] >= INT32_MAX) {\n throw new Error(`trailing dim_size must less than ${\n INT32_MAX} for int32 output type, was ${$sortedSequence2D.shape[1]}`);\n }\n\n const inputs: SearchSortedInputs = {\n sortedSequence: $sortedSequence2D,\n values: $values2D,\n };\n const attrs: SearchSortedAttrs = {side};\n\n return ENGINE.runKernel(SearchSorted, inputs as {}, attrs as {});\n}\n\nexport const searchSorted = /* @__PURE__ */ op({searchSorted_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than or equal to the\n * value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'lowerBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.lowerBound(edges, values);\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.lowerBound(seq, values);\n * result2.print(); // [0, 2, 3]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n * [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n * [0.1, 6.6, 4.5, ]]);\n * const result3 = tf.lowerBound(sortedSequence, values);\n * result3.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n * applying lower bound to each value. The result is not a global index to\n * the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function lowerBound(\n sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n return searchSorted(sortedSequence, values, 'left');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool, MaxPoolAttrs, MaxPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D max pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction maxPool_(\n x: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $x = convertToTensor(x, 'x', 'maxPool');\n const dilations = 1;\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n conv_util.checkPadOnDimRoundingMode('maxPool', pad, dimRoundingMode);\n const inputs: MaxPoolInputs = {x: x4D};\n const attrs: MaxPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n MaxPool, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const maxPool = /* @__PURE__ */ op({maxPool_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D max pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.maxPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n * `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n * `[filterDepth, filterHeight, filterWidth]`.\n * If `filterSize` is a single number,\n * then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n * `[strideDepth, strideHeight, strideWidth]`.\n * If `strides` is a single number,\n * then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1*1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n * \"NDHWC\". Specify the data format of the input and output data. With the\n * default format \"NDHWC\", the data is stored in the order of: [batch,\n * depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPool3d_(\n x: T|TensorLike, filterSize: [number, number, number]|number = [1, 1, 1],\n strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n const $x = convertToTensor(x, 'x', 'maxPool3d');\n\n let x5D = $x as Tensor5D;\n let reshapedTo5D = false;\n if ($x.rank === 4) {\n reshapedTo5D = true;\n x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n }\n\n util.assert(\n x5D.rank === 5,\n () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n util.assert(\n dataFormat === 'NDHWC',\n () => `Error in maxPool3d: Only NDHWC is currently supported, ` +\n `but got dataFormat of ${dataFormat}`);\n checkPadOnDimRoundingMode('maxPool3d', pad, dimRoundingMode);\n const inputs: MaxPool3DInputs = {x: x5D};\n const attrs:\n MaxPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n MaxPool3D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n\n return res;\n}\n\nexport const maxPool3d = /* @__PURE__ */ op({maxPool3d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the 2D max pooling of an image with Argmax index.\n * The indices in argmax are flattened, so that a maximum value at position `[b,\n * y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if\n * include_batch_in_index is False; `((b * height + y) * width + x) * channels\n * +c` if include_batch_in_index is True.\n *\n * The indices returned are always in `[0, height) x [0, width)` before\n * flattening.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n * \"NDHWC\". Specify the data format of the input and output data. With the\n * default format \"NDHWC\", the data is stored in the order of: [batch,\n * depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param includeBatchIndex Defaults to False. Whether to include batch\n * dimension in flattened index of argmax.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPoolWithArgmax_(\n x: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number, pad: 'valid'|'same'|number,\n includeBatchInIndex = false): NamedTensorMap {\n const $x = convertToTensor(x, 'x', 'maxPoolWithArgmax');\n\n const inputs: MaxPoolWithArgmaxInputs = {x: $x};\n const attrs:\n MaxPoolWithArgmaxAttrs = {filterSize, strides, pad, includeBatchInIndex};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const result = ENGINE.runKernel(\n MaxPoolWithArgmax, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor[];\n\n return {result: result[0], indexes: result[1]};\n}\n\nexport const maxPoolWithArgmax = /* @__PURE__ */ op({maxPoolWithArgmax_});\n","/**\n * @license\n * Copyright 2020 Google 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_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n const $x = convertToTensor(x, 'x', 'mean');\n\n const inputs: MeanInputs = {x: $x};\n const attrs: MeanAttrs = {axis, keepDims};\n\n return ENGINE.runKernel(\n Mean, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const mean = /* @__PURE__ */ op({mean_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions, makeZerosTypedArray, sizeFromShape} from '../util';\n\nimport {complex} from './complex';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0.\n *\n * ```js\n * tf.zeros([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Can\n * be 'float32', 'int32' or 'bool'. Defaults to 'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function zeros(\n shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n if (dtype === 'complex64') {\n const real = zeros(shape, 'float32');\n const imag = zeros(shape, 'float32');\n return complex(real, imag);\n }\n const values = makeZerosTypedArray(sizeFromShape(shape), dtype);\n return ENGINE.makeTensor(values, shape, dtype) as Tensor;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {makeOnesTypedArray, sizeFromShape} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\nimport {complex} from './complex';\nimport {zeros} from './zeros';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 1.\n *\n * ```js\n * tf.ones([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n * 'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function ones(\n shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n if (dtype === 'complex64') {\n const real = ones(shape, 'float32');\n const imag = zeros(shape, 'float32');\n return complex(real, imag);\n }\n const values = makeOnesTypedArray(sizeFromShape(shape), dtype);\n return ENGINE.makeTensor(values, shape, dtype) as Tensor;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {matMul} from './mat_mul';\nimport {ones} from './ones';\nimport {reshape} from './reshape';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\n\n/**\n * Broadcasts parameters for evaluation on an N-D grid.\n *\n * Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n * of N-D coordinate arrays for evaluating expressions on an N-D grid.\n *\n * Notes:\n * `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n * When the `indexing` argument is set to 'xy' (the default), the broadcasting\n * instructions for the first two dimensions are swapped.\n * Examples:\n * Calling `const [X, Y] = meshgrid(x, y)` with the tensors\n *\n * ```javascript\n * const x = [1, 2, 3];\n * const y = [4, 5, 6];\n * const [X, Y] = tf.meshgrid(x, y);\n * // X = [[1, 2, 3],\n * // [1, 2, 3],\n * // [1, 2, 3]]\n * // Y = [[4, 4, 4],\n * // [5, 5, 5],\n * // [6, 6, 6]]\n * ```\n *\n * @param x Tensor with rank geq 1.\n * @param y Tensor with rank geq 1.\n * @param indexing\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nexport function meshgrid(\n x?: T|TensorLike, y?: T|TensorLike, {indexing = 'xy'} = {}): T[] {\n if (indexing !== 'xy' && indexing !== 'ij') {\n throw new TypeError(\n `${indexing} is not a valid third argument to meshgrid`);\n }\n if (x === undefined) {\n return [];\n }\n let $x = convertToTensor(\n x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');\n\n if (y === undefined) {\n return [$x];\n }\n let $y = convertToTensor(\n y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');\n\n const w = sizeFromShape($x.shape);\n const h = sizeFromShape($y.shape);\n\n if (indexing === 'xy') {\n $x = reshape($x, [1, -1]) as T;\n $y = reshape($y, [-1, 1]) as T;\n return [\n matMul(ones([h, 1], $x.dtype), $x),\n matMul($y, ones([1, w], $y.dtype)),\n ];\n }\n\n $x = reshape($x, [-1, 1]) as T;\n $y = reshape($y, [1, -1]) as T;\n return [\n matMul($x, ones([1, h], $x.dtype)),\n matMul(ones([w, 1], $y.dtype), $y),\n ];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Minimum, MinimumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the min of a and b (`a < b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `minimumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.minimum(b).print(); // or tf.minimum(a, b)\n * ```\n *\n * ```js\n * // Broadcast minimum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.minimum(b).print(); // or tf.minimum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction minimum_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'minimum');\n let $b = convertToTensor(b, 'b', 'minimum');\n [$a, $b] = makeTypesMatch($a, $b);\n\n if ($a.dtype === 'bool') {\n $a = cast($a, 'int32');\n $b = cast($b, 'int32');\n }\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: MinimumInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Minimum, inputs as unknown as NamedTensorMap);\n}\n\nexport const minimum = /* @__PURE__ */ op({minimum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MirrorPad, MirrorPadAttrs, MirrorPadInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` using mirror padding.\n *\n * This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.\n *\n * ```js\n * const x = tf.range(0, 9).reshape([1, 1, 3, 3]);\n * x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * In \"reflect\" mode, the padded regions do not include the borders,\n * while in \"symmetric\" mode the padded regions do include the borders.\n * For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,\n * then the output is `[1, 2, 3, 2, 1]` in \"reflect\" mode, and\n * `[1, 2, 3, 3, 2]` in \"symmetric\" mode.\n * If `mode` is \"reflect\" then both `paddings[D, 0]` and `paddings[D, 1]`\n * must be no greater than `x.shape[D] - 1`. If mode is \"symmetric\"\n * then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than\n * `x.shape[D]`\n * @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`\n */\n/** @doc {heading: 'Tensors', subheading: 'Transformations'} */\nfunction mirrorPad_(\n x: T|TensorLike, paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric'): T {\n util.assert(\n mode === 'reflect' || mode === 'symmetric',\n () => `Invalid mode. Mode must be either reflect or symmetric. ` +\n `Got ${mode}.`);\n\n const $x = convertToTensor(x, 'x', 'mirrorPad');\n if ($x.rank === 0) {\n throw new Error(\n 'mirrorPad(scalar) is not defined. ' +\n 'Pass non-scalar to mirrorPad');\n }\n util.assert(\n paddings.length === $x.rank,\n () => `Padding doesn't match input. Must be ${$x.rank}. ` +\n `Got ${paddings.length}.`);\n const shapeOffset = mode === 'reflect' ? 1 : 0;\n for (let i = 0; i < $x.rank; i++) {\n util.assert(\n paddings[i].length === 2,\n () => `Invalid number of paddings. Must be length of 2 each.`);\n util.assert(\n paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset &&\n paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset,\n () => `Padding in dimension ${i} cannot be greater than or equal ` +\n `to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` +\n `shape ${$x.shape}`);\n }\n\n const attrs: MirrorPadAttrs = {paddings, mode};\n const inputs: MirrorPadInputs = {x: $x};\n return ENGINE.runKernel(\n MirrorPad, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const mirrorPad = /* @__PURE__ */ op({mirrorPad_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Mod, ModInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the mod of a and b element-wise.\n * `floor(x / y) * y + mod(x, y) = x`\n * Supports broadcasting.\n *\n * We also expose `tf.modStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.mod(b).print(); // or tf.mod(a, b)\n * ```\n *\n * ```js\n * // Broadcast a mod b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.mod(b).print(); // or tf.mod(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mod_(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'mod');\n let $b = convertToTensor(b, 'b', 'mod');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: ModInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(Mod, inputs as unknown as NamedTensorMap);\n}\n\nexport const mod = /* @__PURE__ */ op({mod_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {expandShapeToKeepDim} from './axis_util';\nimport {cast} from './cast';\nimport {mean} from './mean';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {square} from './square';\nimport {sub} from './sub';\n\n/**\n * Calculates the mean and variance of `x`. The mean and variance are\n * calculated by aggregating the contents of `x` across `axes`. If `x` is\n * 1-D and `axes = [0]` this is just the mean and variance of a vector.\n *\n * @param x The input tensor.\n * @param axis The dimension(s) along with to compute mean and\n * variance. By default it reduces all dimensions.\n * @param keepDims If true, the moments have the same dimensionality as the\n * input.\n * @return An object with two keys: `mean` and `variance`.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction moments_(\n x: Tensor|TensorLike, axis: number|number[] = null,\n keepDims = false): {mean: Tensor, variance: Tensor} {\n x = convertToTensor(x, 'x', 'moments');\n const axes = parseAxisParam(axis, x.shape);\n const xMean = mean(x, axes, keepDims);\n let keepDimsShape = xMean.shape;\n if (!keepDims) {\n keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);\n }\n const devSquared =\n square(sub(cast(x, 'float32'), reshape(xMean, keepDimsShape)));\n const variance = mean(devSquared, axes, keepDims);\n return {mean: xMean, variance};\n}\n\nexport const moments = /* @__PURE__ */ op({moments_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor, convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * @docalias (data: Tensor2D, c: Tensor2D, h: Tensor2D): [Tensor2D, Tensor2D]\n */\nexport type LSTMCellFunc = {\n (data: Tensor2D, c: Tensor2D, h: Tensor2D): [Tensor2D, Tensor2D];\n};\n\n/**\n * Computes the next states and outputs of a stack of LSTMCells.\n *\n * Each cell output is used as input to the next cell.\n *\n * Returns `[cellState, cellOutput]`.\n *\n * Derived from tf.contrib.rn.MultiRNNCell.\n *\n * @param lstmCells Array of LSTMCell functions.\n * @param data The input to the cell.\n * @param c Array of previous cell states.\n * @param h Array of previous cell outputs.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction multiRNNCell_(\n lstmCells: LSTMCellFunc[], data: Tensor2D|TensorLike,\n c: Array,\n h: Array): [Tensor2D[], Tensor2D[]] {\n const $data = convertToTensor(data, 'data', 'multiRNNCell');\n const $c = convertToTensorArray(c, 'c', 'multiRNNCell');\n const $h = convertToTensorArray(h, 'h', 'multiRNNCell');\n\n let input = $data;\n const newStates = [];\n for (let i = 0; i < lstmCells.length; i++) {\n const output = lstmCells[i](input, $c[i], $h[i]);\n newStates.push(output[0]);\n newStates.push(output[1]);\n input = output[1];\n }\n const newC: Tensor2D[] = [];\n const newH: Tensor2D[] = [];\n for (let i = 0; i < newStates.length; i += 2) {\n newC.push(newStates[i]);\n newH.push(newStates[i + 1]);\n }\n return [newC, newH];\n}\nexport const multiRNNCell = /* @__PURE__ */ op({multiRNNCell_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multinomial, MultinomialAttrs, MultinomialInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Creates a `tf.Tensor` with values drawn from a multinomial distribution.\n *\n * ```js\n * const probs = tf.tensor([.75, .25]);\n * tf.multinomial(probs, 3).print();\n * ```\n *\n * @param logits 1D array with unnormalized log-probabilities, or\n * 2D array of shape `[batchSize, numOutcomes]`. See the `normalized`\n * parameter.\n * @param numSamples Number of samples to draw for each row slice.\n * @param seed The seed number.\n * @param normalized Whether the provided `logits` are normalized true\n * probabilities (sum to 1). Defaults to false.\n * @return 1D array of shape `[numSamples]`, or 2D array of shape\n * `[batchSize, numSamples]`, depending on the rank of the input.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction multinomial_(\n logits: Tensor1D|Tensor2D|TensorLike, numSamples: number, seed?: number,\n normalized = false): Tensor1D|Tensor2D {\n const $logits = convertToTensor(logits, 'logits', 'multinomial');\n const numOutcomes = $logits.size;\n const origRank = $logits.rank;\n if (numOutcomes < 2) {\n throw new Error(\n `Error in multinomial: you need at least 2 outcomes, but got ` +\n `${numOutcomes}.`);\n }\n if (origRank > 2) {\n throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);\n }\n // TODO(lina128): Investigate correct seed behavior. The code seems not allow\n // setting see to 0.\n seed = seed || Math.random();\n\n // The kernel only accepts (and returns) rank 2 tensors.\n const logits2D: Tensor2D =\n origRank === 1 ? reshape($logits, [1, -1]) : $logits as Tensor2D;\n\n const inputs: MultinomialInputs = {logits: logits2D};\n const attrs: MultinomialAttrs = {numSamples, seed, normalized};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n Multinomial, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor2D;\n\n // tslint:disable-next-line:no-unnecessary-type-assertion\n return origRank === 1 ? reshape(res, [res.size]) as Tensor1D : res;\n}\n\nexport const multinomial = /* @__PURE__ */ op({multinomial_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {NotEqual, NotEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a != b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([0, 2, 3]);\n *\n * a.notEqual(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction notEqual_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'notEqual', 'string_or_numeric');\n let $b = convertToTensor(b, 'b', 'notEqual', 'string_or_numeric');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: NotEqualInputs = {a: $a, b: $b};\n\n return ENGINE.runKernel(NotEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const notEqual = /* @__PURE__ */ op({notEqual_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'onesLike');\n\n const inputs: OnesLikeInputs = {x: $x};\n return ENGINE.runKernel(OnesLike, inputs as unknown as NamedTensorMap);\n}\n\nexport const onesLike = /* @__PURE__ */ op({onesLike_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the outer product of two vectors, `v1` and `v2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([3, 4, 5]);\n *\n * tf.outerProduct(a, b).print();\n * ```\n * @param v1 The first vector in the outer product operation.\n * @param v2 The second vector in the outer product operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction outerProduct_(\n v1: Tensor1D|TensorLike, v2: Tensor1D|TensorLike): Tensor2D {\n const $v1 = convertToTensor(v1, 'v1', 'outerProduct');\n const $v2 = convertToTensor(v2, 'v2', 'outerProduct');\n\n util.assert(\n $v1.rank === 1 && $v2.rank === 1,\n () => `Error in outerProduct: inputs must be rank 1, but got ranks ` +\n `${$v1.rank} and ${$v2.rank}.`);\n\n const v12D = reshape($v1, [-1, 1]);\n const v22D = reshape($v2, [1, -1]);\n return matMul(v12D, v22D);\n}\n\nexport const outerProduct = /* @__PURE__ */ op({outerProduct_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {PadV2, PadV2Attrs, PadV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` with a given value and paddings.\n *\n * This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,\n * refer to `tf.mirrorPad`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `paddings` is of given length.\n * - `tf.pad1d`\n * - `tf.pad2d`\n * - `tf.pad3d`\n * - `tf.pad4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.pad([[1, 2]]).print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * @param constantValue The pad value to use. Defaults to 0.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction pad_(\n x: T|TensorLike, paddings: Array<[number, number]>, constantValue = 0): T {\n const $x = convertToTensor(x, 'x', 'pad');\n if ($x.rank === 0) {\n throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');\n }\n\n const attrs: PadV2Attrs = {paddings, constantValue};\n const inputs: PadV2Inputs = {x: $x};\n return ENGINE.runKernel(\n PadV2, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const pad = /* @__PURE__ */ op({pad_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.\n */\nfunction pad1d_(\n x: Tensor1D|TensorLike, paddings: [number, number],\n constantValue = 0): Tensor1D {\n assert(\n paddings.length === 2,\n () => 'Invalid number of paddings. Must be length of 2.');\n return pad(x, [paddings], constantValue);\n}\n\nexport const pad1d = /* @__PURE__ */ op({pad1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.\n */\nfunction pad2d_(\n x: Tensor2D|TensorLike, paddings: [[number, number], [number, number]],\n constantValue = 0): Tensor2D {\n assert(\n paddings.length === 2 && paddings[0].length === 2 &&\n paddings[1].length === 2,\n () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}\n\nexport const pad2d = /* @__PURE__ */ op({pad2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.\n */\nfunction pad3d_(\n x: Tensor3D|TensorLike,\n paddings: [[number, number], [number, number], [number, number]],\n constantValue = 0): Tensor3D {\n assert(\n paddings.length === 3 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2,\n () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}\n\nexport const pad3d = /* @__PURE__ */ op({pad3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.\n */\nfunction pad4d_(\n x: Tensor4D|TensorLike,\n paddings:\n [\n [number, number], [number, number], [number, number], [number, number]\n ],\n constantValue = 0): Tensor4D {\n assert(\n paddings.length === 4 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2 &&\n paddings[3].length === 2,\n () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}\n\nexport const pad4d = /* @__PURE__ */ op({pad4d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation divides \"spatial\" dimensions `[1, ..., M]` of the input into\n * a grid of blocks of shape `blockShape`, and interleaves these blocks with\n * the \"batch\" dimension (0) such that in the output, the spatial\n * dimensions `[1, ..., M]` correspond to the position within the grid,\n * and the batch dimension combines both the position within a spatial block\n * and the original batch position. Prior to division into blocks,\n * the spatial dimensions of the input are optionally zero padded\n * according to `paddings`. See below for a precise description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);\n * const blockShape = [2, 2];\n * const paddings = [[0, 0], [0, 0]];\n *\n * x.spaceToBatchND(blockShape, paddings).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=\n * 0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad\n * from input dimension `i + 1`, which corresponds to spatial dimension `i`. It\n * is required that\n * `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input\n * according to `paddings` to produce `padded` of shape paddedShape.\n *\n * 2. Reshape `padded` to `reshapedPadded` of shape:\n * `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`\n *\n * 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`\n * of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the\n * batch dimension, producing an output tensor of shape:\n * `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction spaceToBatchND_(\n x: T|TensorLike, blockShape: number[], paddings: number[][]): T {\n const $x = convertToTensor(x, 'x', 'spaceToBatchND');\n\n util.assert(\n $x.rank >= 1 + blockShape.length,\n () => `input rank ${$x.rank} should be > than [blockShape] ${\n blockShape.length}`);\n\n util.assert(\n paddings.length === blockShape.length,\n () => `paddings.shape[0] ${\n paddings.length} must be equal to [blockShape] ${blockShape.length}`);\n\n util.assert(\n $x.shape.reduce(\n (a, b, i) => {\n if (i > 0 && i <= blockShape.length) {\n return a &&\n ((b + paddings[i - 1][0] + paddings[i - 1][1]) %\n blockShape[i - 1] ===\n 0);\n }\n return a;\n },\n true),\n () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${\n paddings.toString()} must be divisible by blockShapes ${\n blockShape.toString()}`);\n\n const inputs: SpaceToBatchNDInputs = {x: $x};\n const attrs: SpaceToBatchNDAttrs = {blockShape, paddings};\n\n return ENGINE.runKernel(\n SpaceToBatchND, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const spaceToBatchND = /* @__PURE__ */ op({spaceToBatchND_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {avgPool} from './avg_pool';\nimport {batchToSpaceND} from './batch_to_space_nd';\nimport * as conv_util from './conv_util';\nimport {maxPool} from './max_pool';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {spaceToBatchND} from './space_to_batch_nd';\n\n/**\n * Performs an N-D pooling operation\n *\n * @param input The input tensor, of rank 4 or rank 3 of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param windowShape The filter size: `[filterHeight, filterWidth]`. If\n * `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param poolingType The type of pooling, either 'max' or 'avg'.\n * @param pad The type of padding algorithm:\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_guides/python/nn#Convolution](\n * https://www.tensorflow.org/api_guides/python/nn#Convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction pool_(\n input: T|TensorLike, windowShape: [number, number]|number,\n poolingType: 'avg'|'max',\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dilations?: [number, number]|number, strides?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil') {\n if (dilations == null) {\n dilations = [1, 1];\n }\n if (strides == null) {\n strides = 1;\n }\n if (pad === 0) {\n pad = 'valid';\n }\n\n const $x = convertToTensor(input, 'x', 'maxPool');\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in pool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = conv_util.computePool2DInfo(\n x4D.shape, windowShape, strides, dilations, pad);\n const dilation: [number, number] =\n [convInfo.dilationHeight, convInfo.dilationWidth];\n\n // The following implementation does batchToSpace(pool(spaceToBatch(x)))\n // whenever dilation > 1 since the TF kernels do not support dilation > 1.\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037\n\n let basePadding: number[][];\n if (pad === 'same') {\n basePadding = withSpaceToBatchBasePaddings(\n [convInfo.filterHeight, convInfo.filterWidth], dilation);\n } else {\n basePadding = [[0, 0], [0, 0]];\n }\n\n const isDilationOne = dilation[0] === 1 && dilation[1] === 1;\n const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings(\n [convInfo.inHeight, convInfo.inWidth], dilation, basePadding);\n const convertedPad = isDilationOne ? pad : 'valid';\n const convertedX =\n isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);\n\n const forwardOp = poolingType === 'avg' ?\n () => avgPool(convertedX, windowShape, strides, convertedPad,\n dimRoundingMode) :\n () => maxPool(convertedX, windowShape, strides, convertedPad,\n dimRoundingMode);\n const y = forwardOp();\n\n const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n\n return res as T;\n}\n\n// Helper function to compute crops and paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184\nfunction requiredSpaceToBatchPaddings(\n inputShape: [number, number], blockShape: [number, number],\n basePadding: number[][]) {\n const padStart = basePadding.map(b => b[0]);\n const origPadEnd = basePadding.map(b => b[1]);\n const fullInputShape = inputShape.concat(padStart, origPadEnd);\n const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);\n const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);\n const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);\n const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);\n return [paddings, crops];\n}\n\n// Helper function to compute base paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524\nfunction withSpaceToBatchBasePaddings(\n filterShape: [number, number], dilation: [number, number]) {\n // Spatial dimensions of the filters and the upsampled filters in which we\n // introduce (rate - 1) zeros between consecutive filter values.\n const dilatedFilterShape = filterShape.map((s, i) => {\n return s + (s - 1) * (dilation[i] - 1);\n });\n const padExtraShape = dilatedFilterShape.map(s => s - 1);\n\n // When padding is odd, we pad more at end, following the same\n // convention as conv2d.\n const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));\n const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);\n return padExtraShape.map((_, i) => {\n return [padExtraStart[i], padExtraEnd[i]];\n });\n}\n\nexport const pool = /* @__PURE__ */ op({pool_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prelu, PreluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise with parametric alphas.\n *\n * `x < 0 ? alpha * x : f(x) = x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n * const alpha = tf.scalar(0.1);\n *\n * x.prelu(alpha).print(); // or tf.prelu(x, alpha)\n * ```\n * @param x The input tensor.\n * @param alpha Scaling factor for negative values.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction prelu_(x: T|TensorLike, alpha: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'prelu');\n const $alpha = convertToTensor(alpha, 'alpha', 'prelu');\n\n const inputs: PreluInputs = {x: $x, alpha: $alpha};\n return ENGINE.runKernel(Prelu, inputs as unknown as NamedTensorMap);\n}\n\nexport const prelu = /* @__PURE__ */ op({prelu_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prod, ProdAttrs, ProdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes the product of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.prod().print(); // or tf.prod(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.prod(axis).print(); // or tf.prod(x, axis)\n * ```\n *\n * @param x The input tensor to compute the product over. If the dtype is `bool`\n * it will be converted to `int32` and the output dtype will be `int32`.\n * @param axis The dimension(s) to reduce. By default it reduces\n * all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction prod_(\n x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n let $x = convertToTensor(x, 'x', 'prod');\n\n if ($x.dtype === 'bool') {\n // bool is not an allowed type for the underlying kernel.\n $x = cast($x, 'int32');\n }\n\n const inputs: ProdInputs = {x: $x};\n const attrs: ProdAttrs = {axis, keepDims};\n\n return ENGINE.runKernel(\n Prod, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const prod = /* @__PURE__ */ op({prod_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedGather, RaggedGatherAttrs, RaggedGatherInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather ragged slices from params axis 0 according to indices.\n *\n * @param paramsNestedSplits: A list of at least 1 Tensor with type 'int32' The\n * nestedRowSplits tensors that define the row-partitioning for the params\n * RaggedTensor input.\n * @param paramsDenseValues: A Tensor. The flatValues for the params\n * RaggedTensor.\n * @param indices: A Tensor. Must be one of type: int32. Indices in the\n * outermost dimension of params of the values that should be gathered.\n * @param outputRaggedRank: An int that is >= 0. The ragged rank of the output\n * RaggedTensor. outputNestedSplits will contain this number of rowSplits\n * tensors. This value should equal indices.shape.ndims + params.raggedRank\n * - 1.\n * @return A map with the following properties:\n * - outputNestedSplits: A list of outputRaggedRank Tensor objects with the\n * same type as paramsNestedSplits.\n * - outputDenseValues: A Tensor. Has the same type as paramsDenseValues.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\n\ninterface RaggedGatherMap {\n outputNestedSplits: Tensor[];\n outputDenseValues: Tensor;\n}\n\nfunction raggedGather_(\n paramsNestedSplits: Tensor[], paramsDenseValues: Tensor|TensorLike,\n indices: Tensor|TensorLike, outputRaggedRank: number): RaggedGatherMap {\n const $paramsNestedSplits = paramsNestedSplits.map(\n (t, i) => convertToTensor(t, `tensors${i}`, 'raggedGather', 'int32'));\n const $paramsDenseValues =\n convertToTensor(paramsDenseValues, 'paramsDenseValues', 'raggedGather');\n const $indices = convertToTensor(indices, 'indices', 'raggedGather', 'int32');\n\n const inputs: RaggedGatherInputs = {\n paramsNestedSplits: $paramsNestedSplits,\n paramsDenseValues: $paramsDenseValues,\n indices: $indices,\n };\n const attrs: RaggedGatherAttrs = {outputRaggedRank};\n\n const result: Tensor[] =\n ENGINE.runKernel(RaggedGather, inputs as {}, attrs as {});\n return {\n outputNestedSplits: result.slice(0, result.length - 1),\n outputDenseValues: result[result.length - 1],\n };\n}\n\nexport const raggedGather = /* @__PURE__ */ op({raggedGather_});\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedRange, RaggedRangeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns a RaggedTensor result composed from rtDenseValues and rtNestedSplits,\n * such that result[i] = [starts[i], starts[i] + deltas[i], ..., limits[i]]).\n *\n * @param starts: A Tensor. Must be one of the following types:\n * 'float32', 'int32'. The starts of each range.\n * @param limits: A Tensor. Must have the same type as starts. The limits of\n * each range.\n * @param deltas: A Tensor. Must have the same type as starts. The deltas of\n * each range.\n * @return A map with the following properties:\n * - rtNestedSplits: A Tensor of type 'int32'.\n * - rtDenseValues: A Tensor. Has the same type as starts.\n */\n\nfunction raggedRange_(\n starts: Tensor|TensorLike, limits: Tensor|TensorLike,\n deltas: Tensor|TensorLike): NamedTensorMap {\n const $starts = convertToTensor(starts, 'starts', 'raggedRange');\n const $limits =\n convertToTensor(limits, 'limits', 'raggedRange', $starts.dtype);\n const $deltas =\n convertToTensor(deltas, 'deltas', 'raggedRange', $starts.dtype);\n\n const inputs: RaggedRangeInputs = {\n starts: $starts,\n limits: $limits,\n deltas: $deltas,\n };\n\n const result: Tensor[] = ENGINE.runKernel(RaggedRange, inputs as {});\n return {\n rtNestedSplits: result[0],\n rtDenseValues: result[1],\n };\n}\n\nexport const raggedRange = /* @__PURE__ */ op({raggedRange_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedTensorToTensor, RaggedTensorToTensorAttrs, RaggedTensorToTensorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Create a dense tensor from a ragged tensor, possibly altering its shape.\n *\n * The raggedTensorToTensor op creates a dense tensor from am array of row\n * partition tensors, a value vector, and default values. If the shape is\n * unspecified, the minimal shape required to contain all the elements in the\n * ragged tensor (the natural shape) will be used. If some dimensions are left\n * unspecified, then the size of the natural shape is used in that dimension.\n *\n * The defaultValue will be broadcast to the output shape. After that, the\n * values from the ragged tensor overwrite the default values. Note that the\n * defaultValue must have less dimensions than the value.\n *\n * The row partition tensors are in the order of the dimensions. At present, the\n * types can be: \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n * \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n * \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n * is preceded by \"FIRST_DIM_SIZE\".\n * ```\n * @param shape: A Tensor. Must be one of the following types: 'int32'. The\n * desired shape of the output tensor. If left unspecified (empty), the\n * minimal shape required to contain all the elements in the ragged tensor\n * (the natural shape) will be used. If some dimensions are left\n * unspecified, then the size of the natural shape is used in that\n * dimension.\n *\n * Note that dense dimensions cannot be modified by the shape argument.\n * Trying to change the size of a dense dimension will cause the op to fail.\n * Examples: natural shape: [4, 5, 6] shape: -1 output shape: [4, 5, 6]\n *\n * natural shape: [4, 5, 6] shape: [3, -1, 2] output shape: [3, 5, 2]\n *\n * natural shape: [4, 5, 6] shape: [3, 7, 2] output shape: [3, 7, 2]\n * @param values: A Tensor. A 1D tensor representing the values of the ragged\n * tensor.\n * @param defaultValue: A Tensor. Must have the same type as values. The\n * defaultValue when the shape is larger than the ragged tensor. The\n * defaultValue is broadcast until it is the shape of the output tensor,\n * and then overwritten by values in the ragged tensor. The default value\n * must be compatible with this broadcast operation, and must have fewer\n * dimensions than the value tensor.\n * @param rowPartitionTensors: A list of at least 1 Tensor objects with the same\n * type in: 'int32'.\n * @param rowPartitionTypes: A list of strings. The types of the row partition\n * tensors. At present, these can be:\n * \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n * \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n * \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then\n * it is preceeded by \"FIRST_DIM_SIZE\". The tensors are in the order of\n * the dimensions.\n * @return A Tensor. Has the same type as values.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\nfunction raggedTensorToTensor_(\n shape: Tensor|TensorLike, values: Tensor|TensorLike,\n defaultValue: Tensor|TensorLike, rowPartitionTensors: Tensor[],\n rowPartitionTypes: string[]): Tensor {\n const $shape =\n convertToTensor(shape, 'shape', 'raggedTensorToTensor', 'int32');\n const $values = convertToTensor(values, 'values', 'raggedTensorToTensor');\n const $defaultValue = convertToTensor(\n defaultValue, 'defaultValue', 'raggedTensorToTensor', $values.dtype);\n const $rowPartitionTensors = rowPartitionTensors.map(\n (t, i) =>\n convertToTensor(t, `tensors${i}`, 'raggedTensorToTensor', 'int32'));\n\n const inputs: RaggedTensorToTensorInputs = {\n shape: $shape,\n values: $values,\n defaultValue: $defaultValue,\n rowPartitionTensors: $rowPartitionTensors\n };\n const attrs: RaggedTensorToTensorAttrs = {rowPartitionTypes};\n\n return ENGINE.runKernel(RaggedTensorToTensor, inputs as {}, attrs as {});\n}\n\nexport const raggedTensorToTensor = /* @__PURE__ */ op({raggedTensorToTensor_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {sizeFromShape} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a random number generator\n * function defined by the user.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param randFunction A random number generator function which is called\n * for each element in the output tensor.\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction rand_(\n shape: ShapeMap[R], randFunction: () => number,\n dtype?: DataType): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n const size = sizeFromShape(shape);\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n for (let i = 0; i < size; i++) {\n values[i] = randFunction();\n }\n return ENGINE.makeTensor(values, shape, dtype) as Tensor;\n}\n\nexport const rand = /* @__PURE__ */ op({rand_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as seedrandom from 'seedrandom';\n\nimport {expectNumbersClose, testEpsilon} from '../test_util';\nimport {TypedArray} from '../types';\n\nexport interface RandomBase {\n nextValue(): number;\n}\n\nexport interface RandomGamma {\n nextValue(): number;\n}\n\nexport interface RandNormalDataTypes {\n float32: Float32Array;\n int32: Int32Array;\n}\n\nexport interface RandGammaDataTypes {\n float32: Float32Array;\n int32: Int32Array;\n}\n\n// https://en.wikipedia.org/wiki/Marsaglia_polar_method\nexport class MPRandGauss implements RandomBase {\n private mean: number;\n private stdDev: number;\n private nextVal: number;\n private dtype?: keyof RandNormalDataTypes;\n private truncated?: boolean;\n private upper?: number;\n private lower?: number;\n private random: seedrandom.prng;\n\n constructor(\n mean: number, stdDeviation: number, dtype?: keyof RandNormalDataTypes,\n truncated?: boolean, seed?: number) {\n this.mean = mean;\n this.stdDev = stdDeviation;\n this.dtype = dtype;\n this.nextVal = NaN;\n this.truncated = truncated;\n if (this.truncated) {\n this.upper = this.mean + this.stdDev * 2;\n this.lower = this.mean - this.stdDev * 2;\n }\n const seedValue = seed ? seed : Math.random();\n this.random = seedrandom.alea(seedValue.toString());\n }\n\n /** Returns next sample from a Gaussian distribution. */\n public nextValue(): number {\n if (!isNaN(this.nextVal)) {\n const value = this.nextVal;\n this.nextVal = NaN;\n return value;\n }\n\n let resultX: number, resultY: number;\n let isValid = false;\n while (!isValid) {\n let v1: number, v2: number, s: number;\n do {\n v1 = 2 * this.random() - 1;\n v2 = 2 * this.random() - 1;\n s = v1 * v1 + v2 * v2;\n } while (s >= 1 || s === 0);\n\n const mul = Math.sqrt(-2.0 * Math.log(s) / s);\n resultX = this.mean + this.stdDev * v1 * mul;\n resultY = this.mean + this.stdDev * v2 * mul;\n\n if (!this.truncated || this.isValidTruncated(resultX)) {\n isValid = true;\n }\n }\n\n if (!this.truncated || this.isValidTruncated(resultY)) {\n this.nextVal = this.convertValue(resultY);\n }\n return this.convertValue(resultX);\n }\n\n /** Handles proper rounding for non-floating-point numbers. */\n private convertValue(value: number): number {\n if (this.dtype == null || this.dtype === 'float32') {\n return value;\n }\n return Math.round(value);\n }\n\n /** Returns true if less than 2-standard-deviations from the mean. */\n private isValidTruncated(value: number): boolean {\n return value <= this.upper && value >= this.lower;\n }\n}\n\n// Marsaglia, George, and Wai Wan Tsang. 2000. \"A Simple Method for Generating\n// Gamma Variables.\"\nexport class RandGamma implements RandomGamma {\n private alpha: number;\n private beta: number;\n private d: number;\n private c: number;\n private dtype?: keyof RandGammaDataTypes;\n private randu: seedrandom.prng;\n private randn: MPRandGauss;\n\n constructor(\n alpha: number, beta: number, dtype: keyof RandGammaDataTypes,\n seed?: number) {\n this.alpha = alpha;\n this.beta = 1 / beta; // convert rate to scale parameter\n this.dtype = dtype;\n\n const seedValue = seed ? seed : Math.random();\n this.randu = seedrandom.alea(seedValue.toString());\n this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());\n\n if (alpha < 1) {\n this.d = alpha + (2 / 3);\n } else {\n this.d = alpha - (1 / 3);\n }\n this.c = 1 / Math.sqrt(9 * this.d);\n }\n\n /** Returns next sample from a gamma distribution. */\n public nextValue(): number {\n let x2: number, v0: number, v1: number, x: number, u: number, v: number;\n while (true) {\n do {\n x = this.randn.nextValue();\n v = 1 + (this.c * x);\n } while (v <= 0);\n v *= v * v;\n x2 = x * x;\n v0 = 1 - (0.331 * x2 * x2);\n v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));\n u = this.randu();\n if (u < v0 || Math.log(u) < v1) {\n break;\n }\n }\n v = (1 / this.beta) * this.d * v;\n if (this.alpha < 1) {\n v *= Math.pow(this.randu(), 1 / this.alpha);\n }\n return this.convertValue(v);\n }\n /** Handles proper rounding for non-floating-point numbers. */\n private convertValue(value: number): number {\n if (this.dtype === 'float32') {\n return value;\n }\n return Math.round(value);\n }\n}\n\nexport class UniformRandom implements RandomBase {\n private min: number;\n private range: number;\n private random: seedrandom.prng;\n private dtype?: keyof RandNormalDataTypes;\n\n constructor(\n min = 0, max = 1, dtype?: keyof RandNormalDataTypes,\n seed?: string|number) {\n this.min = min;\n this.range = max - min;\n this.dtype = dtype;\n if (seed == null) {\n seed = Math.random();\n }\n if (typeof seed === 'number') {\n seed = seed.toString();\n }\n\n if (!this.canReturnFloat() && this.range <= 1) {\n throw new Error(\n `The difference between ${min} - ${max} <= 1 and dtype is not float`);\n }\n this.random = seedrandom.alea(seed);\n }\n\n /** Handles proper rounding for non floating point numbers. */\n private canReturnFloat = () =>\n (this.dtype == null || this.dtype === 'float32');\n\n private convertValue(value: number): number {\n if (this.canReturnFloat()) {\n return value;\n }\n return Math.round(value);\n }\n\n nextValue() {\n return this.convertValue(this.min + this.range * this.random());\n }\n}\n\nexport function jarqueBeraNormalityTest(values: TypedArray|number[]) {\n // https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test\n const n = values.length;\n const s = skewness(values);\n const k = kurtosis(values);\n const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));\n // JB test requires 2-degress of freedom from Chi-Square @ 0.95:\n // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm\n const CHI_SQUARE_2DEG = 5.991;\n if (jb > CHI_SQUARE_2DEG) {\n throw new Error(`Invalid p-value for JB: ${jb}`);\n }\n}\n\nexport function expectArrayInMeanStdRange(\n actual: TypedArray|number[], expectedMean: number, expectedStdDev: number,\n epsilon?: number) {\n if (epsilon == null) {\n epsilon = testEpsilon();\n }\n const actualMean = mean(actual);\n expectNumbersClose(actualMean, expectedMean, epsilon);\n expectNumbersClose(\n standardDeviation(actual, actualMean), expectedStdDev, epsilon);\n}\n\nfunction mean(values: TypedArray|number[]) {\n let sum = 0;\n for (let i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum / values.length;\n}\n\nfunction standardDeviation(values: TypedArray|number[], mean: number) {\n let squareDiffSum = 0;\n for (let i = 0; i < values.length; i++) {\n const diff = values[i] - mean;\n squareDiffSum += diff * diff;\n }\n return Math.sqrt(squareDiffSum / values.length);\n}\n\nfunction kurtosis(values: TypedArray|number[]) {\n // https://en.wikipedia.org/wiki/Kurtosis\n const valuesMean = mean(values);\n const n = values.length;\n let sum2 = 0;\n let sum4 = 0;\n for (let i = 0; i < n; i++) {\n const v = values[i] - valuesMean;\n sum2 += Math.pow(v, 2);\n sum4 += Math.pow(v, 4);\n }\n return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);\n}\n\nfunction skewness(values: TypedArray|number[]) {\n // https://en.wikipedia.org/wiki/Skewness\n const valuesMean = mean(values);\n const n = values.length;\n let sum2 = 0;\n let sum3 = 0;\n for (let i = 0; i < n; i++) {\n const v = values[i] - valuesMean;\n sum2 += Math.pow(v, 2);\n sum3 += Math.pow(v, 3);\n }\n return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {RandGamma} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a gamma distribution.\n *\n * ```js\n * tf.randomGamma([2, 2], 1).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param alpha The shape parameter of the gamma distribution.\n * @param beta The inverse scale parameter of the gamma distribution. Defaults\n * to 1.\n * @param dtype The data type of the output. Defaults to float32.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomGamma_(\n shape: ShapeMap[R], alpha: number, beta = 1,\n dtype: 'float32'|'int32' = 'float32', seed?: number): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n if (beta == null) {\n beta = 1;\n }\n if (dtype == null) {\n dtype = 'float32';\n }\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new Error(`Unsupported data type ${dtype}`);\n }\n const rgamma = new RandGamma(alpha, beta, dtype, seed);\n const res = buffer(shape, dtype);\n for (let i = 0; i < res.values.length; i++) {\n res.values[i] = rgamma.nextValue();\n }\n return res.toTensor();\n}\n\nexport const randomGamma = /* @__PURE__ */ op({randomGamma_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * ```js\n * tf.randomNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomNormal_(\n shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n seed?: number): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n if (dtype != null && (dtype as DataType) === 'bool') {\n throw new Error(`Unsupported data type ${dtype}`);\n }\n const randGauss =\n new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);\n const res = buffer(shape, dtype);\n for (let i = 0; i < res.values.length; i++) {\n res.values[i] = randGauss.nextValue();\n }\n return res.toTensor();\n}\n\nexport const randomNormal = /* @__PURE__ */ op({randomNormal_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {op} from './operation';\nimport {randomNormal} from './random_normal';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * The generated values will have mean 0 and standard deviation 1.\n *\n * ```js\n * tf.randomStandardNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomStandardNormal_(\n shape: ShapeMap[R], dtype?: 'float32'|'int32', seed?: number): Tensor {\n if (dtype != null && (dtype as DataType) === 'bool') {\n throw new Error(`Unsupported data type ${dtype}`);\n }\n return randomNormal(shape, 0, 1, dtype, seed);\n}\n\nexport const randomStandardNormal = /* @__PURE__ */ op({randomStandardNormal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {UniformRandom} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a uniform distribution.\n *\n * The generated values follow a uniform distribution in the range [minval,\n * maxval). The lower bound minval is included in the range, while the upper\n * bound maxval is excluded.\n *\n * ```js\n * tf.randomUniform([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param minval The lower bound on the range of random values to generate.\n * Defaults to 0.\n * @param maxval The upper bound on the range of random values to generate.\n * Defaults to 1.\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n * @param seed An optional int. Defaults to 0. If seed is set to be non-zero,\n * the random number generator is seeded by the given seed. Otherwise, it is\n * seeded by a random seed.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomUniform_(\n shape: ShapeMap[R], minval = 0, maxval = 1, dtype: DataType = 'float32',\n seed?: number|string): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n const res = buffer(shape, dtype);\n const random = new UniformRandom(minval, maxval, null, seed);\n for (let i = 0; i < res.values.length; i++) {\n res.values[i] = random.nextValue();\n }\n return res.toTensor();\n}\n\nexport const randomUniform = /* @__PURE__ */ op({randomUniform_});\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\nimport {op} from './operation';\nimport {randomUniform} from './random_uniform';\n\n/**\n * Creates a `tf.Tensor` with integers sampled from a uniform distribution.\n *\n * The generated values are uniform integers in the range [minval, maxval). The\n * lower bound minval is included in the range, while the upper bound maxval is\n * excluded.\n *\n * ```js\n * tf.randomUniformInt([2, 2], 0, 10).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param minval Inclusive lower bound on the generated integers.\n * @param maxval Exclusive upper bound on the generated integers.\n * @param seed An optional int. Defaults to 0. If seed is set to be non-zero,\n * the random number generator is seeded by the given seed. Otherwise, it is\n * seeded by a random seed.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomUniformInt_(\n shape: ShapeMap[R], minval: number, maxval: number,\n seed?: number|string): Tensor {\n // TODO(mattsoulanille): Handle optional seed2 input.\n return randomUniform(shape, minval, maxval, 'int32', seed);\n}\n\nexport const randomUniformInt = /* @__PURE__ */ op({randomUniformInt_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Range, RangeAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Creates a new `tf.Tensor1D` filled with the numbers in the range provided.\n *\n * The tensor is a half-open interval meaning it includes start, but\n * excludes stop. Decrementing ranges and negative step values are also\n * supported.\n *\n *\n * ```js\n * tf.range(0, 9, 2).print();\n * ```\n *\n * @param start An integer start value\n * @param stop An integer stop value\n * @param step An integer increment (will default to 1 or -1)\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function range(\n start: number, stop: number, step = 1,\n dtype: 'float32'|'int32' = 'float32'): Tensor1D {\n if (step === 0) {\n throw new Error('Cannot have a step of zero');\n }\n\n const attrs: RangeAttrs = {start, stop, step, dtype};\n\n return ENGINE.runKernel(Range, {} /* inputs */,\n attrs as unknown as NamedAttrMap);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'reciprocal');\n\n const inputs: ReciprocalInputs = {x: $x};\n return ENGINE.runKernel(Reciprocal, inputs as unknown as NamedTensorMap);\n}\nexport const reciprocal = /* @__PURE__ */ op({reciprocal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu, ReluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear element-wise: `max(x, 0)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.relu().print(); // or tf.relu(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n * `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'relu');\n\n const inputs: ReluInputs = {x: $x};\n\n return ENGINE.runKernel(Relu, inputs as unknown as NamedTensorMap);\n}\n\nexport const relu = /* @__PURE__ */ op({relu_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu6, Relu6Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 8]);\n *\n * x.relu6().print(); // or tf.relu6(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n * `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu6_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'relu6');\n\n const inputs: Relu6Inputs = {x: $x};\n\n return ENGINE.runKernel(Relu6, inputs as unknown as NamedTensorMap);\n}\n\nexport const relu6 = /* @__PURE__ */ op({relu6_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reverse, ReverseAttrs, ReverseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reverses a `tf.Tensor` along a specified axis.\n *\n * Also available are stricter rank-specific methods that assert that `x` is\n * of the given rank:\n * - `tf.reverse1d`\n * - `tf.reverse2d`\n * - `tf.reverse3d`\n * - `tf.reverse4d`\n *\n * Except `tf.reverse1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.reverse().print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.reverse(axis).print();\n * ```\n * @param x The input tensor to be reversed.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction reverse_(\n x: T|TensorLike, axis?: number|number[]): T {\n const $x = convertToTensor(x, 'x', 'reverse');\n\n const inputs: ReverseInputs = {x: $x};\n const attrs: ReverseAttrs = {dims: axis};\n\n return ENGINE.runKernel(\n Reverse, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const reverse = /* @__PURE__ */ op({reverse_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor1D`.\n *\n * @param x The input tensor.\n */\nfunction reverse1d_(x: Tensor1D|TensorLike): Tensor1D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 1,\n () => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);\n return reverse($x, 0);\n}\n\nexport const reverse1d = /* @__PURE__ */ op({reverse1d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor2D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse2d_(x: Tensor2D|TensorLike, axis?: number|number[]): Tensor2D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 2,\n () => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);\n return reverse($x, axis);\n}\n\nexport const reverse2d = /* @__PURE__ */ op({reverse2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor3D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse3d_(x: Tensor3D|TensorLike, axis?: number|number[]): Tensor3D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 3,\n () => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);\n return reverse($x, axis);\n}\n\nexport const reverse3d = /* @__PURE__ */ op({reverse3d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor4D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n * range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse4d_(x: Tensor4D|TensorLike, axis?: number|number[]): Tensor4D {\n const $x = convertToTensor(x, 'x', 'reverse');\n util.assert(\n $x.rank === 4,\n () => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);\n return reverse($x, axis);\n}\n\nexport const reverse4d = /* @__PURE__ */ op({reverse4d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Round, RoundInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes round of input `tf.Tensor` element-wise: `round(x)`.\n * It implements banker's rounding.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.round().print(); // or tf.round(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction round_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'round');\n const inputs: RoundInputs = {x: $x};\n\n return ENGINE.runKernel(Round, inputs as unknown as NamedTensorMap);\n}\n\nexport const round = /* @__PURE__ */ op({round_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Rsqrt, RsqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes reciprocal of square root of the input `tf.Tensor` element-wise:\n * `y = 1 / sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.rsqrt().print(); // or tf.rsqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction rsqrt_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'rsqrt', 'float32');\n\n const inputs: RsqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Rsqrt, inputs as unknown as NamedTensorMap);\n}\nexport const rsqrt = /* @__PURE__ */ op({rsqrt_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Selu, SeluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes scaled exponential linear element-wise.\n *\n * `x < 0 ? scale * alpha * (exp(x) - 1) : scale * x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.selu().print(); // or tf.selu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction selu_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'selu');\n\n const inputs: SeluInputs = {x: $x};\n\n return ENGINE.runKernel(Selu, inputs as unknown as NamedTensorMap);\n}\n\nexport const selu = /* @__PURE__ */ op({selu_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport {depthwiseConv2d} from './depthwise_conv2d';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * 2-D convolution with separable filters.\n *\n * Performs a depthwise convolution that acts separately on channels followed\n * by a pointwise convolution that mixes channels. Note that this is\n * separability between dimensions [1, 2] and 3, not spatial separability\n * between dimensions 1 and 2.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](\n * https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param depthwiseFilter The depthwise filter tensor, rank 4, of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is\n * the filter used in the first step.\n * @param pointwiseFilter The pointwise filter tensor, rank 4, of shape\n * `[1, 1, inChannels * channelMultiplier, outChannels]`. This is\n * the filter used in the second step.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels]. Only \"NHWC\" is currently supported.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction separableConv2d_(\n x: T|TensorLike, depthwiseFilter: Tensor4D|TensorLike,\n pointwiseFilter: Tensor4D|TensorLike, strides: [number, number]|number,\n pad: 'valid'|'same', dilation: [number, number]|number = [1, 1],\n dataFormat: 'NHWC'|'NCHW' = 'NHWC'): T {\n const $x = convertToTensor(x, 'x', 'separableConv2d');\n const $depthwiseFilter =\n convertToTensor(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');\n const $pointwiseFilter =\n convertToTensor(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n\n if (dataFormat === 'NCHW') {\n throw new Error(\n 'separableConv2d currently does not support dataFormat NCHW; only ' +\n 'NHWC is supported');\n }\n\n util.assert(\n x4D.rank === 4,\n () => `Error in separableConv2d: input must be rank 4, but got ` +\n `rank ${x4D.rank}.`);\n util.assert(\n $depthwiseFilter.rank === 4,\n () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +\n `got rank ${$depthwiseFilter.rank}.`);\n util.assert(\n $pointwiseFilter.rank === 4,\n () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +\n `got rank ${$depthwiseFilter.rank}.`);\n util.assert(\n $pointwiseFilter.shape[0] === 1,\n () =>\n `Error in separableConv2d: the first dimension of pointwise filter ` +\n ` must be 1, but got ${$pointwiseFilter.shape[0]}.`);\n util.assert(\n $pointwiseFilter.shape[1] === 1,\n () => `Error in separableConv2d: the second dimension of pointwise ` +\n `filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);\n\n const inChannels = $depthwiseFilter.shape[2];\n const channelMultiplier = $depthwiseFilter.shape[3];\n util.assert(\n $pointwiseFilter.shape[2] === inChannels * channelMultiplier,\n () =>\n `Error in separableConv2d: the third dimension of pointwise filter ` +\n `must be ${inChannels * channelMultiplier}, ` +\n `but got ${$pointwiseFilter.shape[2]}.`);\n\n const depthwise = depthwiseConv2d(\n x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);\n const pointwiseStride = 1;\n const res =\n conv2d(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res as T;\n}\n\nexport const separableConv2d = /* @__PURE__ */ op({separableConv2d_});\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, TensorBuffer} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\n/**\n * Computes the difference between two lists of numbers.\n *\n * Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`\n * that represents all values that are in `x` but not in `y`. The returned\n * Tensor `out` is sorted in the same order that the numbers appear in `x`\n * (duplicates are preserved). This operation also returns a Tensor indices that\n * represents the position of each out element in `x`. In other words:\n *\n * `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`\n *\n * ```js\n * const x = [1, 2, 3, 4, 5, 6];\n * const y = [1, 3, 5];\n *\n * const [out, indices] = await tf.setdiff1dAsync(x, y);\n * out.print(); // [2, 4, 6]\n * indices.print(); // [1, 3, 5]\n * ```\n *\n * @param x 1-D Tensor. Values to keep.\n * @param y 1-D Tensor. Must have the same type as x. Values to exclude in the\n * output.\n * @returns Promise of Tensor tuple [out, indices].\n * out: Tensor with the same type as x.\n * indices: A Tensor of type int32.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nasync function setdiff1dAsync_(\n x: Tensor|TensorLike, y: Tensor|TensorLike): Promise<[Tensor, Tensor]> {\n const $x = convertToTensor(x, 'x', 'setdiff1d');\n const $y = convertToTensor(y, 'y', 'setdiff1d');\n\n util.assert(\n $x.dtype === $y.dtype,\n () => `x and y should have the same dtype, but got x (${\n $x.dtype}) and y (${$y.dtype}).`);\n\n util.assert(\n $x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);\n\n util.assert(\n $y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);\n\n const xVals = await $x.data();\n const yVals = await $y.data();\n const ySet = new Set(yVals);\n\n let outputSize = 0;\n for (let i = 0; i < xVals.length; i++) {\n if (!ySet.has(xVals[i])) {\n outputSize++;\n }\n }\n\n const buffer = new TensorBuffer([outputSize], $x.dtype);\n const indices = new TensorBuffer([outputSize], 'int32');\n for (let i = 0, p = 0; i < xVals.length; i++) {\n if (!ySet.has(xVals[i])) {\n buffer.values[p] = xVals[i];\n indices.values[p] = i;\n p++;\n }\n }\n return [buffer.toTensor(), indices.toTensor()];\n}\nexport const setdiff1dAsync = setdiff1dAsync_;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sign, SignInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns an element-wise indication of the sign of a number.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);\n *\n * x.sign().print(); // or tf.sign(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sign_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sign');\n const inputs: SignInputs = {x: $x};\n return ENGINE.runKernel(Sign, inputs as unknown as NamedTensorMap);\n}\nexport const sign = /* @__PURE__ */ op({sign_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sin, SinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes sin of the input Tensor element-wise: `sin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.sin().print(); // or tf.sin(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sin_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sin', 'float32');\n\n const inputs: SinInputs = {x: $x};\n\n return ENGINE.runKernel(Sin, inputs as unknown as NamedTensorMap);\n}\nexport const sin = /* @__PURE__ */ op({sin_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sinh, SinhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.sinh().print(); // or tf.sinh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sinh_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'sinh');\n const inputs: SinhInputs = {x: $x};\n\n return ENGINE.runKernel(Sinh, inputs as unknown as NamedTensorMap);\n}\nexport const sinh = /* @__PURE__ */ op({sinh_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 1D slice from 1D array starting at coordinates `begin` and is\n * of length `size`. See `slice` for details.\n */\nfunction slice1d_(\n x: Tensor1D|TensorLike, begin: number, size: number): Tensor1D {\n const $x = convertToTensor(x, 'x', 'slice1d');\n util.assert(\n $x.rank === 1,\n () =>\n `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, [begin], [size]);\n}\nexport const slice1d = /* @__PURE__ */ op({slice1d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 2D slice from a 2D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice2d_(\n x: Tensor2D|TensorLike, begin: [number, number],\n size: [number, number]): Tensor2D {\n const $x = convertToTensor(x, 'x', 'slice2d');\n util.assert(\n $x.rank === 2,\n () =>\n `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, begin, size);\n}\nexport const slice2d = /* @__PURE__ */ op({slice2d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 3D slice from a 3D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice3d_(\n x: Tensor3D|TensorLike, begin: [number, number, number],\n size: [number, number, number]): Tensor3D {\n const $x = convertToTensor(x, 'x', 'slice3d');\n util.assert(\n $x.rank === 3,\n () =>\n `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, begin, size);\n}\nexport const slice3d = /* @__PURE__ */ op({slice3d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 4D slice from a 4D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice4d_(\n x: Tensor4D|TensorLike, begin: [number, number, number, number],\n size: [number, number, number, number]): Tensor4D {\n const $x = convertToTensor(x, 'x', 'slice4d');\n util.assert(\n $x.rank === 4,\n () =>\n `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);\n return slice($x, begin, size);\n}\nexport const slice4d = /* @__PURE__ */ op({slice4d_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softmax, SoftmaxAttrs, SoftmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the softmax normalized vector given the logits.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n *\n * a.softmax().print(); // or tf.softmax(a)\n * ```\n *\n * ```js\n * const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);\n *\n * a.softmax().print(); // or tf.softmax(a)\n * ```\n *\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n * which indicates the last dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction softmax_(logits: T|TensorLike, dim = -1): T {\n const $logits = convertToTensor(logits, 'logits', 'softmax', 'float32');\n\n if (dim === -1) {\n dim = $logits.rank - 1;\n }\n if (dim !== $logits.rank - 1) {\n throw Error(\n 'Softmax along a non-last dimension is not yet supported. ' +\n `Logits was rank ${$logits.rank} and dim was ${dim}`);\n }\n\n const inputs: SoftmaxInputs = {logits: $logits};\n const attrs: SoftmaxAttrs = {dim};\n\n return ENGINE.runKernel(\n Softmax, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const softmax = /* @__PURE__ */ op({softmax_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FFT, FFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the inner-most\n * dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.fft().print(); // tf.spectral.fft(x).print();\n * ```\n * @param input The complex input to compute an fft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction fft_(input: Tensor): Tensor {\n assert(\n input.dtype === 'complex64',\n () => `The dtype for tf.spectral.fft() must be complex64 ` +\n `but got ${input.dtype}.`);\n\n const inputs: FFTInputs = {input};\n\n return ENGINE.runKernel(FFT, inputs as unknown as NamedTensorMap);\n}\n\nexport const fft = /* @__PURE__ */ op({fft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {IFFT, IFFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Inverse fast Fourier transform.\n *\n * Computes the inverse 1-dimensional discrete Fourier transform over the\n * inner-most dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.ifft().print(); // tf.spectral.ifft(x).print();\n * ```\n * @param input The complex input to compute an ifft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction ifft_(input: Tensor): Tensor {\n assert(\n input.dtype === 'complex64',\n () => `The dtype for tf.spectral.ifft() must be complex64 ` +\n `but got ${input.dtype}.`);\n\n const inputs: IFFTInputs = {input};\n\n return ENGINE.runKernel(IFFT, inputs as unknown as NamedTensorMap);\n}\n\nexport const ifft = /* @__PURE__ */ op({ifft_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {reverse} from '../reverse';\nimport {scalar} from '../scalar';\nimport {slice} from '../slice';\n\nimport {ifft} from './ifft';\n\n/**\n * Inversed real value input fast Fourier transform.\n *\n * Computes the 1-dimensional inversed discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([0, 0, 0]);\n * const x = tf.complex(real, imag);\n *\n * x.irfft().print();\n * ```\n * @param input The real value input to compute an irfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction irfft_(input: Tensor): Tensor {\n const innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = input.size / innerDimensionSize;\n let ret: Tensor;\n if (innerDimensionSize <= 2) {\n const complexInput = reshape(input, [batch, innerDimensionSize]);\n ret = ifft(complexInput);\n } else {\n // The length of unique components of the DFT of a real-valued signal\n // is 2 * (input_len - 1)\n const outputShape = [batch, 2 * (innerDimensionSize - 1)];\n const realInput = reshape(real(input), [batch, innerDimensionSize]);\n const imagInput = reshape(imag(input), [batch, innerDimensionSize]);\n\n const realConjugate =\n reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);\n const imagConjugate: Tensor2D = mul(\n reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1),\n scalar(-1));\n\n const r = concat([realInput, realConjugate], 1);\n const i = concat([imagInput, imagConjugate], 1);\n const complexInput =\n reshape(complex(r, i), [outputShape[0], outputShape[1]]);\n ret = ifft(complexInput);\n }\n ret = real(ret);\n // reshape the result if the input is 3D tensor.\n if (input.rank === 3 && input.shape[0] !== 0) {\n const temp = ret;\n const batch = input.shape[0];\n ret = reshape(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);\n temp.dispose();\n }\n return ret;\n}\n\nexport const irfft = /* @__PURE__ */ op({irfft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {SplitV, SplitVAttrs, SplitVInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Splits a `tf.Tensor` into sub tensors.\n *\n * If `numOrSizeSplits` is a number, splits `x` along dimension `axis`\n * into `numOrSizeSplits` smaller tensors.\n * Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.\n *\n * If `numOrSizeSplits` is a number array, splits `x` into\n * `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the\n * same size as `x` except along dimension `axis` where the size is\n * `numOrSizeSplits[i]`.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);\n * const [a, b] = tf.split(x, 2, 1);\n * a.print();\n * b.print();\n *\n * const [c, d, e] = tf.split(x, [1, 2, 1], 1);\n * c.print();\n * d.print();\n * e.print();\n * ```\n *\n * @param x The input tensor to split.\n * @param numOrSizeSplits Either an integer indicating the number of\n * splits along the axis or an array of integers containing the sizes of\n * each output tensor along the axis. If a number then it must evenly divide\n * `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.\n * Can contain one -1 indicating that dimension is to be inferred.\n * @param axis The dimension along which to split. Defaults to 0 (the first\n * dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction split_(\n x: Tensor|TensorLike, numOrSizeSplits: number[]|number, axis = 0): T[] {\n const $x = convertToTensor(x, 'x', 'split');\n\n const inputs: SplitVInputs = {x: $x};\n const attr: SplitVAttrs = {numOrSizeSplits, axis};\n\n return ENGINE.runKernel(\n SplitV, inputs as unknown as NamedTensorMap,\n attr as unknown as NamedAttrMap) as unknown as T[];\n}\n\nexport const split = /* @__PURE__ */ op({split_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {assert} from '../../util';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {split} from '../split';\nimport {zeros} from '../zeros';\nimport {zerosLike} from '../zeros_like';\n\nimport {fft} from './fft';\n\n/**\n * Real value input fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n *\n * real.rfft().print();\n * ```\n * @param input The real value input to compute an rfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction rfft_(input: Tensor, fftLength?: number): Tensor {\n assert(\n input.dtype === 'float32',\n () => `The dtype for rfft() must be real value but got ${input.dtype}`);\n\n let innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = input.size / innerDimensionSize;\n\n let adjustedInput: Tensor;\n if (fftLength != null && fftLength < innerDimensionSize) {\n // Need to crop\n const begin = input.shape.map(v => 0);\n const size = input.shape.map(v => v);\n size[input.shape.length - 1] = fftLength;\n adjustedInput = slice(input, begin, size);\n innerDimensionSize = fftLength;\n } else if (fftLength != null && fftLength > innerDimensionSize) {\n // Need to pad with zeros\n const zerosShape = input.shape.map(v => v);\n zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;\n adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);\n innerDimensionSize = fftLength;\n } else {\n adjustedInput = input;\n }\n\n // Complement the input with zero imaginary numbers.\n const zerosInput = zerosLike(adjustedInput);\n const complexInput =\n reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);\n\n const ret = fft(complexInput);\n\n // Exclude complex conjugations. These conjugations are put symmetrically.\n const half = Math.floor(innerDimensionSize / 2) + 1;\n const realValues = real(ret);\n const imagValues = imag(ret);\n const realComplexConjugate = split(\n realValues, [half, innerDimensionSize - half],\n realValues.shape.length - 1);\n const imagComplexConjugate = split(\n imagValues, [half, innerDimensionSize - half],\n imagValues.shape.length - 1);\n\n const outputShape = adjustedInput.shape.slice();\n outputShape[adjustedInput.shape.length - 1] = half;\n\n return reshape(\n complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);\n}\n\nexport const rfft = /* @__PURE__ */ op({rfft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SquaredDifference, SquaredDifferenceInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns (a - b) * (a - b) element-wise.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)\n * ```\n *\n * ```js\n * // Broadcast squared difference a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction squaredDifference_(\n a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n let $a = convertToTensor(a, 'a', 'squaredDifference');\n let $b = convertToTensor(b, 'b', 'squaredDifference');\n [$a, $b] = makeTypesMatch($a, $b);\n\n assertAndGetBroadcastShape($a.shape, $b.shape);\n\n const inputs: SquaredDifferenceInputs = {a: $a, b: $b};\n const attrs = {};\n\n return ENGINE.runKernel(\n SquaredDifference, inputs as unknown as NamedTensorMap, attrs);\n}\n\nexport const squaredDifference = /* @__PURE__ */ op({squaredDifference_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {squeezeShape} from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Removes dimensions of size 1 from the shape of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);\n * x.squeeze().print();\n * ```\n *\n * @param x The input tensor to be squeezed.\n * @param axis An optional list of numbers. If specified, only\n * squeezes the dimensions listed. The dimension index starts at 0. It\n * is an error to squeeze a dimension that is not 1.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction squeeze_(x: Tensor|TensorLike, axis?: number[]): T {\n const $x = convertToTensor(x, 'x', 'squeeze', 'string_or_numeric');\n return reshape($x, squeezeShape($x.shape, axis).newShape) as T;\n}\n\nexport const squeeze = /* @__PURE__ */ op({squeeze_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Pack, PackAttrs, PackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.stack([a, b, c]).print();\n * ```\n *\n * @param tensors A list of tensor objects with the same shape and dtype.\n * @param axis The axis to stack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction stack_(\n tensors: Array, axis = 0): Tensor {\n const $tensors =\n convertToTensorArray(tensors, 'tensors', 'stack', 'string_or_numeric');\n\n util.assert(\n $tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');\n\n if ($tensors.length > 0) {\n util.assert(\n axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');\n }\n\n const inputs: PackInputs = $tensors;\n const attrs: PackAttrs = {axis};\n\n return ENGINE.runKernel(\n Pack, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const stack = /* @__PURE__ */ op({stack_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Step, StepAttrs, StepInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha`\n *\n * ```js\n * const x = tf.tensor1d([0, 2, -1, -3]);\n *\n * x.step(.5).print(); // or tf.step(x, .5)\n * ```\n * @param x The input tensor.\n * @param alpha The gradient when input is negative. Defaults to 0.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction step_(x: T|TensorLike, alpha = 0.0): T {\n const $x = convertToTensor(x, 'x', 'step');\n\n const inputs: StepInputs = {x: $x};\n const attrs: StepAttrs = {alpha};\n\n return ENGINE.runKernel(\n Step, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\nexport const step = /* @__PURE__ */ op({step_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {StridedSlice, StridedSliceAttrs, StridedSliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a strided slice of a tensor.\n *\n * Roughly speaking, this op extracts a slice of size (end-begin)/stride from\n * the given input tensor (x). Starting at the location specified by begin the\n * slice continues by adding stride to the index until all dimensions are not\n * less than end. Note that a stride can be negative, which causes a reverse\n * slice.\n *\n * ```js\n * const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],\n * [3, 2, 3]);\n * t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print() // [[[3, 3, 3]]]\n * t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print() // [[[3, 3, 3],\n * // [4, 4, 4]]]\n * t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],\n * // [3, 3, 3]]]\n * ```\n *\n * @param x The tensor to stride slice.\n * @param begin The coordinates to start the slice from.\n * @param end: The coordinates to end the slice at.\n * @param strides: The size of the slice.\n * @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored\n * and the fullest possible range in that dimension is used instead.\n * @param endMask: If the ith bit of endMask is set, end[i] is ignored\n * and the fullest possible range in that dimension is used instead.\n * @param shrinkAxisMask: a bitmask where bit i implies that\n * the ith specification should shrink the dimensionality. begin and end must\n * imply a slice of size 1 in the dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction stridedSlice_(\n x: Tensor|TensorLike, begin: number[], end: number[], strides?: number[],\n beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0,\n shrinkAxisMask = 0): Tensor {\n const $x = convertToTensor(x, 'x', 'stridedSlice', 'string_or_numeric');\n\n const inputs: StridedSliceInputs = {x: $x};\n const attrs: StridedSliceAttrs = {\n begin,\n end,\n strides,\n beginMask,\n endMask,\n ellipsisMask,\n newAxisMask,\n shrinkAxisMask\n };\n\n return ENGINE.runKernel(\n StridedSlice, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const stridedSlice = /* @__PURE__ */ op({stridedSlice_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tan, TanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes tan of the input `tf.Tensor` element-wise, `tan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.tan().print(); // or tf.tan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tan_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'tan', 'float32');\n\n const inputs: TanInputs = {x: $x};\n\n return ENGINE.runKernel(Tan, inputs as unknown as NamedTensorMap);\n}\nexport const tan = /* @__PURE__ */ op({tan_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike1D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor1d` as it makes the code more readable.\n *\n * ```js\n * tf.tensor1d([1, 2, 3]).print();\n * ```\n *\n * @param values The values of the tensor. Can be array of numbers,\n * or a `TypedArray`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor1d(values: TensorLike1D, dtype?: DataType): Tensor1D {\n assertNonNull(values);\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 1) {\n throw new Error('tensor1d() requires values to be a flat/TypedArray');\n }\n const shape: number[] = null;\n return makeTensor(values, shape, inferredShape, dtype) as Tensor1D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike2D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor2d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor2d([[1, 2], [3, 4]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor2d(\n values: TensorLike2D, shape?: [number, number],\n dtype?: DataType): Tensor2D {\n assertNonNull(values);\n if (shape != null && shape.length !== 2) {\n throw new Error('tensor2d() requires shape to have two numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 2 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor2d() requires values to be number[][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor2d() requires shape to be provided when `values` ' +\n 'are a flat/TypedArray');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor2D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {TensorScatterUpdate, TensorScatterUpdateAttrs, TensorScatterUpdateInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\nimport * as scatter_nd_util from './scatter_nd_util';\n\n/**\n * Creates a new tensor by applying sparse updates to individual\n * values or slices to the passed in tensor according to\n * indices. This operator is the similar to scatterNd op, except that the\n * udpates are scattered on an existing tensor (as opposed to a zero-tensor).\n *\n * If indices contains duplicates, then we pick the last update for the index.\n *\n * If an out of bound index is found on CPU, an error is returned.\n *\n * Warning: There are some GPU specific semantics for this operation.\n * - If an out of bound index is found, the index is ignored.\n * - The order in which updates are applied is nondeterministic, so the output\n * will be nondeterministic if indices contains duplicates.\n * ```js\n * const shape = [8];\n * const tensor = tf.ones(shape);\n * const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');\n * const updates = tf.tensor1d([9, 10, 11, 12]);\n *\n * tf.tensorScatterUpdate(tensor, indices, updates).print();\n * //[1, 11, 1, 10, 9, 1, 1, 12]\n * ```\n *\n * @param tensor A Tensor. Tensor to copy/update.\n * @param indices The tensor contains the indices into the output tensor, must\n * have at least 2 axes: (num_updates, index_depth).\n * @param updates The tensor contains the value for the indices.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction tensorScatterUpdate_(\n tensor: Tensor|TensorLike, indices: Tensor|TensorLike,\n updates: Tensor|TensorLike): Tensor {\n const $tensor = convertToTensor(tensor, 'tensor', 'tensorScatterupdate');\n const $indices =\n convertToTensor(indices, 'indices', 'tensorScatterupdate', 'int32');\n const $updates = convertToTensor(updates, 'updates', 'tensorScatterupdate');\n scatter_nd_util.validateInput($updates, $indices, $tensor.shape);\n if ($tensor.dtype !== $updates.dtype) {\n throw new Error(\n `tensor and updates must have the same dtype, instead they are ${\n $tensor.dtype} and ${$updates.dtype}.`);\n }\n\n const inputs: TensorScatterUpdateInputs = {\n tensor: $tensor,\n indices: $indices,\n updates: $updates\n };\n const attrs: TensorScatterUpdateAttrs = {};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n TensorScatterUpdate, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor;\n}\n\nexport const tensorScatterUpdate = op({tensorScatterUpdate_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {TopK, TopKAttrs, TopKInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Finds the values and indices of the `k` largest entries along the last\n * dimension.\n *\n * If the input is a vector (rank=1), finds the k largest entries in the vector\n * and outputs their values and indices as vectors. Thus values[j] is the j-th\n * largest entry in input, and its index is indices[j].\n * For higher rank inputs, computes the top k entries along the last dimension.\n *\n * If two elements are equal, the lower-index element appears first.\n *\n * ```js\n * const a = tf.tensor2d([[1, 5], [4, 3]]);\n * const {values, indices} = tf.topk(a);\n * values.print();\n * indices.print();\n * ```\n * @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.\n * @param k Number of top elements to look for along the last dimension.\n * @param sorted If true, the resulting `k` elements will be sorted by the\n * values in descending order.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction topk_(\n x: T|TensorLike, k = 1, sorted = true): {values: T, indices: T} {\n const $x = convertToTensor(x, 'x', 'topk');\n if ($x.rank === 0) {\n throw new Error('topk() expects the input to be of rank 1 or higher');\n }\n const lastDim = $x.shape[$x.shape.length - 1];\n\n if (k < 0) {\n throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);\n }\n\n if (k > lastDim) {\n throw new Error(\n `'k' passed to topk() must be <= the last dimension (${lastDim}) ` +\n `but got ${k}`);\n }\n\n const inputs: TopKInputs = {x: $x};\n const attrs: TopKAttrs = {k, sorted};\n\n const [values, indices] = ENGINE.runKernel(\n TopK, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as [T, T];\n\n return {values, indices};\n}\n\nexport const topk = /* @__PURE__ */ op({topk_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a truncated normal\n * distribution.\n *\n * ```js\n * tf.truncatedNormal([2, 2]).print();\n * ```\n *\n * The generated values follow a normal distribution with specified mean and\n * standard deviation, except that values whose magnitude is more than 2\n * standard deviations from the mean are dropped and re-picked.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output tensor.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction truncatedNormal_(\n shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n seed?: number): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n if (dtype != null && (dtype as DataType) === 'bool') {\n throw new Error(`Unsupported data type $ { dtype }`);\n }\n const randGauss =\n new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);\n const res = buffer(shape, dtype);\n for (let i = 0; i < res.values.length; i++) {\n res.values[i] = randGauss.nextValue();\n }\n return res.toTensor();\n}\n\nexport const truncatedNormal = /* @__PURE__ */ op({truncatedNormal_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unique, UniqueAttrs, UniqueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Finds unique elements along an axis of a tensor.\n *\n * It returns a tensor `values` containing all of the unique elements along the\n * `axis` of the given tensor `x` in the same order that they occur along the\n * `axis` in `x`; `x` does not need to be sorted. It also returns a tensor\n * `indices` the same size as the number of the elements in `x` along the `axis`\n * dimension. It contains the index in the unique output `values`.\n *\n * ```js\n * // A 1-D tensor\n * const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);\n * const {values, indices} = tf.unique(a);\n * values.print(); // [1, 2, 4, 7, 8,]\n * indices.print(); // [0, 0, 1, 2, 2, 2, 3, 4, 4]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=0\n * //\n * // 'a' is: [[1, 0, 0],\n * // [1, 0, 0],\n * // [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 0)\n * values.print(); // [[1, 0, 0],\n * // [2, 0, 0]]\n * indices.print(); // [0, 0, 1]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=1\n * //\n * // 'a' is: [[1, 0, 0],\n * // [1, 0, 0],\n * // [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 1)\n * values.print(); // [[1, 0],\n * // [1, 0],\n * // [2, 0]]\n * indices.print(); // [0, 1, 1]\n * ```\n * @param x A tensor (int32, string, bool).\n * @param axis The axis of the tensor to find the unique elements.\n * @returns [uniqueElements, indices] (see above for details)\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction unique_(\n x: T|TensorLike, axis = 0): {values: T, indices: Tensor1D} {\n const $x = convertToTensor(x, 'x', 'unique', 'string_or_numeric');\n assert($x.rank > 0, () => 'The input tensor must be at least 1D');\n\n const inputs: UniqueInputs = {x: $x};\n const attrs: UniqueAttrs = {axis};\n const [values, indices] = ENGINE.runKernel(\n Unique, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as [T, Tensor1D];\n return {values, indices};\n}\n\nexport const unique = /* @__PURE__ */ op({unique_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert, isInt} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Computes the sum along segments of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');\n * const numSegments = 3;\n *\n * x.unsortedSegmentSum(segmentIds, numSegments).print()\n * //or tf.unsortedSegmentSum(x, segmentIds, numSegments)\n * ```\n * @param x The `tf.Tensor` that will be summed along its segments.\n * @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s\n * dimension along the `axis`. Maps each element of `x` to a segment.\n * @param numSegments The number of distinct `segmentIds`.\n *\n * @doc {heading: 'Operations', subheading: 'Segment'}\n */\nfunction unsortedSegmentSum_(\n x: T|TensorLike, segmentIds: Tensor1D|TensorLike, numSegments: number): T {\n const $x = convertToTensor(x, 'x', 'unsortedSegmentSum');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');\n assert(isInt(numSegments), () => 'numSegments must be of dtype int');\n\n const inputs: UnsortedSegmentSumInputs = {x: $x, segmentIds: $segmentIds};\n const attrs: UnsortedSegmentSumAttrs = {numSegments};\n\n return ENGINE.runKernel(\n UnsortedSegmentSum, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const unsortedSegmentSum = /* @__PURE__ */ op({unsortedSegmentSum_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unpack, UnpackAttrs, UnpackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * tf.unstack(a).forEach(tensor => tensor.print());\n * ```\n *\n * @param x A tensor object.\n * @param axis The axis to unstack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction unstack_(x: Tensor|TensorLike, axis = 0): Tensor[] {\n const $x = convertToTensor(x, 'x', 'unstack', 'string_or_numeric');\n util.assert(\n axis >= -$x.shape.length && axis < $x.shape.length,\n () =>\n `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);\n\n const inputs: UnpackInputs = {value: $x};\n const attrs: UnpackAttrs = {axis};\n\n return ENGINE.runKernel(\n Unpack, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const unstack = /* @__PURE__ */ op({unstack_});\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than the value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'upperBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * const values = tf.tensor1d([0, 4, 10]);\n * const result = tf.upperBound(seq, values);\n * result.print(); // [1, 2, 5]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n * applying upper bound to each value. The result is not a global index to\n * the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function upperBound(\n sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n return searchSorted(sortedSequence, values, 'right');\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor, Variable} from '../tensor';\nimport {DataType, Rank} from '../types';\n\n/**\n * Creates a new variable with the provided initial value.\n * ```js\n * const x = tf.variable(tf.tensor([1, 2, 3]));\n * x.assign(tf.tensor([4, 5, 6]));\n *\n * x.print();\n * ```\n *\n * @param initialValue Initial value for the tensor.\n * @param trainable If true, optimizers are allowed to update it.\n * @param name Name of the variable. Defaults to a unique id.\n * @param dtype If set, initialValue will be converted to the given type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function variable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n return ENGINE.makeVariable(initialValue, trainable, name, dtype) as\n Variable;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** An implementation of the Where kernel shared between cpu and webgl */\n\nimport {buffer} from '../ops/buffer';\nimport {Tensor2D} from '../tensor';\nimport {TypedArray} from '../types';\n\nexport function whereImpl(condShape: number[], condVals: TypedArray): Tensor2D {\n const indices = [];\n for (let i = 0; i < condVals.length; i++) {\n if (condVals[i]) {\n indices.push(i);\n }\n }\n\n const inBuffer = buffer(condShape, 'int32');\n\n const out = buffer([indices.length, condShape.length], 'int32');\n for (let i = 0; i < indices.length; i++) {\n const loc = inBuffer.indexToLoc(indices[i]);\n const offset = i * condShape.length;\n out.values.set(loc, offset);\n }\n return out.toTensor() as Tensor2D;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {whereImpl} from '../backends/where_impl';\nimport {Tensor, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\n/**\n * Returns the coordinates of true elements of condition.\n *\n * The coordinates are returned in a 2-D tensor where the first dimension (rows)\n * represents the number of true elements, and the second dimension (columns)\n * represents the coordinates of the true elements. Keep in mind, the shape of\n * the output tensor can vary depending on how many true values there are in\n * input. Indices are output in row-major order. The resulting tensor has the\n * shape `[numTrueElems, condition.rank]`.\n *\n * This is analogous to calling the python `tf.where(cond)` without an x or y.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const result = await tf.whereAsync(cond);\n * result.print();\n * ```\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nasync function whereAsync_(condition: Tensor|TensorLike): Promise {\n const $condition =\n convertToTensor(condition, 'condition', 'whereAsync', 'bool');\n const vals = await $condition.data();\n const res = whereImpl($condition.shape, vals);\n if (condition !== $condition) {\n $condition.dispose();\n }\n return res;\n}\n\nexport const whereAsync = whereAsync_;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {gather} from './gather';\nimport {reshape} from './reshape';\nimport {squeeze} from './squeeze';\nimport {whereAsync} from './where_async';\n\n/**\n * Apply boolean mask to tensor.\n *\n * ```js\n * const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);\n * const mask = tf.tensor1d([1, 0, 1], 'bool');\n * const result = await tf.booleanMaskAsync(tensor, mask);\n * result.print();\n * ```\n *\n * @param tensor N-D tensor.\n * @param mask K-D boolean tensor, K <= N and K must be known statically.\n * @param axis A 0-D int Tensor representing the axis in tensor to mask from.\n * By default, axis is 0 which will mask from the first dimension.\n * Otherwise K + axis <= N.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nasync function booleanMaskAsync_(\n tensor: Tensor|TensorLike, mask: Tensor|TensorLike,\n axis?: number): Promise {\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_(\n v: T|TensorLike, x: T|TensorLike, decay: number|Scalar,\n step?: number|Scalar, zeroDebias = true): T {\n const $v = convertToTensor(v, 'v', 'movingAverage');\n const $x = convertToTensor(x, 'x', 'movingAverage');\n const $decay = convertToTensor(decay, 'decay', 'movingAverage');\n\n assertTypesMatch($v, $x);\n util.assert(\n util.arraysEqual($v.shape, $x.shape), () => 'Shape mismatch in v and x');\n\n const one = scalar(1);\n const oneMinusDecay = sub(one, $decay);\n\n let update = mul(sub($x, $v), oneMinusDecay);\n if (zeroDebias) {\n util.assert(\n step != null, () => 'When using zeroDebias: true, step is required.');\n const $step = convertToTensor(step, 'step', 'movingAverage');\n update = div(update, sub(one, pow($decay, $step)));\n }\n return add($v, update);\n}\n\nexport const movingAverage = /* @__PURE__ */ op({movingAverage_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ScatterNd, ScatterNdAttrs, ScatterNdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\nimport * as scatter_nd_util from './scatter_nd_util';\n\n/**\n * Creates a new tensor by applying sparse updates to individual\n * values or slices within a zero tensor of the given shape tensor according to\n * indices. This operator is the inverse of the `tf.gatherND` operator which\n * extracts values or slices from a given tensor.\n *\n * ```js\n * const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');\n * const updates = tf.tensor1d([9, 10, 11, 12]);\n * const shape = [8];\n * tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]\n * ```\n *\n * @param indices The tensor contains the indices into the output tensor.\n * @param updates The tensor contains the value for the indices.\n * @param shape: The shape of the output tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction scatterND_(\n indices: Tensor|TensorLike, updates: Tensor|TensorLike,\n shape: ShapeMap[R]): Tensor {\n assertNonNegativeIntegerDimensions(shape);\n const $indices = convertToTensor(indices, 'indices', 'scatterND', 'int32');\n const $updates = convertToTensor(updates, 'updates', 'scatterND');\n scatter_nd_util.validateInput($updates, $indices, shape);\n\n const inputs: ScatterNdInputs = {indices: $indices, updates: $updates};\n const attrs: ScatterNdAttrs = {shape};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n ScatterNd, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor;\n}\n\nexport const scatterND = /* @__PURE__ */ op({scatterND_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SparseToDense, SparseToDenseAttrs, SparseToDenseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport * as sparse_to_dense from '../ops/sparse_to_dense_util';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ScalarLike, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Converts a sparse representation into a dense tensor.\n *\n * Builds an array dense with shape outputShape such that:\n *\n * // If sparseIndices is scalar\n * dense[i] = (i == sparseIndices ? sparseValues : defaultValue)\n *\n * // If sparseIndices is a vector, then for each i\n * dense[sparseIndices[i]] = sparseValues[i]\n *\n * // If sparseIndices is an n by d matrix, then for each i in [0, n)\n * dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]\n * All other values in dense are set to defaultValue. If sparseValues is a\n * scalar, all sparse indices are set to this single value.\n *\n * If indices are repeated the final value is summed over all values for those\n * indices.\n *\n * ```js\n * const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');\n * const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');\n * const shape = [8];\n * tf.sparseToDense(indices, values, shape).print();\n * ```\n *\n * @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.\n * sparseIndices[i] contains the complete index where sparseValues[i] will be\n * placed.\n * @param sparseValues A 0-D or 1-D Tensor. Values\n * corresponding to each row of sparseIndices, or a scalar value to be used for\n * all sparse indices.\n * @param outputShape Shape of the dense output tensor. The type is inferred.\n * @param defaultValue Scalar. Value to set for indices not specified in\n * sparseIndices. Defaults to zero.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction sparseToDense_(\n sparseIndices: Tensor|TensorLike, sparseValues: Tensor|TensorLike,\n outputShape: ShapeMap[R], defaultValue: Scalar|ScalarLike = 0): Tensor {\n assertNonNegativeIntegerDimensions(outputShape);\n\n const $sparseIndices =\n convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');\n const $sparseValues = convertToTensor(\n sparseValues, 'sparseValues', 'sparseToDense', 'string_or_numeric');\n const $defaultValue = convertToTensor(\n defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);\n\n sparse_to_dense.validateInput(\n $sparseIndices, $sparseValues, outputShape, $defaultValue);\n\n const inputs: SparseToDenseInputs = {\n sparseIndices: $sparseIndices,\n sparseValues: $sparseValues,\n defaultValue: $defaultValue\n };\n\n const attrs: SparseToDenseAttrs = {outputShape};\n\n return ENGINE.runKernel(\n SparseToDense, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const sparseToDense = /* @__PURE__ */ op({sparseToDense_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {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 */\nimport {ENGINE} from '../engine';\nimport {GatherNd, GatherNdInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather slices from input tensor into a Tensor with shape specified by\n * `indices`.\n *\n * `indices` is a K-dimensional integer tensor, best thought of as a\n * (K-1)-dimensional tensor of indices into input, where each element defines a\n * slice of input:\n * output[\\\\(i_0, ..., i_{K-2}\\\\)] = input[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n *\n * Whereas in `tf.gather`, `indices` defines slices into the first dimension of\n * input, in `tf.gatherND`, `indices` defines slices into the first N dimensions\n * of input, where N = indices.shape[-1].\n *\n * The last dimension of indices can be at most the rank of input:\n * indices.shape[-1] <= input.rank\n *\n * The last dimension of `indices` corresponds to elements\n * (if indices.shape[-1] == input.rank) or slices\n * (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of\n * input.\n * The output tensor has shape\n * indices.shape[:-1] + input.shape[indices.shape[-1]:]\n *\n * Note that on CPU, if an out of bound index is found, an error is returned. On\n * GPU, if an out of bound index is found, a 0 is stored in the corresponding\n * output value.\n *\n * ```js\n * const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');\n * const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);\n * tf.gatherND(input, indices).print() // [10, 11]\n * ```\n *\n * @param x The tensor from which to gather values.\n * @param indices Index tensor, must be of type int32.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction gatherND_(x: Tensor|TensorLike, indices: Tensor|TensorLike): Tensor {\n const $indices = convertToTensor(indices, 'indices', 'gatherND', 'int32');\n const $x = convertToTensor(x, 'x', 'gatherND', 'string_or_numeric');\n\n const inputs: GatherNdInputs = {params: $x, indices: $indices};\n\n return ENGINE.runKernel(GatherNd, inputs as unknown as NamedTensorMap);\n}\n\nexport const gatherND = /* @__PURE__ */ op({gatherND_});\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {add} from './add';\nimport {div} from './div';\nimport {getNoiseShape} from './dropout_util';\nimport {floor} from './floor';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {randomUniform} from './random_uniform';\n\n/**\n * Computes dropout.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 2, 1]);\n * const rate = 0.75;\n * const output = tf.dropout(x, rate);\n * output.print();\n * ```\n *\n * @param x A floating point Tensor or TensorLike.\n * @param rate A float in the range [0, 1). The probability that each element\n * of x is discarded.\n * @param noiseShape An array of numbers of type int32, representing the\n * shape for randomly generated keep/drop flags. If the noiseShape has null\n * value, it will be automatically replaced with the x's relative dimension\n * size. Optional.\n * @param seed Used to create random seeds. Optional.\n * @returns A Tensor of the same shape of x.\n *\n * @doc {heading: 'Operations', subheading: 'Dropout'}\n */\nfunction dropout_(\n x: Tensor|TensorLike, rate: number, noiseShape?: number[],\n seed?: number|string): Tensor {\n const $x = convertToTensor(x, 'x', 'dropout');\n\n util.assert(\n $x.dtype === 'float32',\n () => `x has to be a floating point tensor since it's going to be ` +\n `scaled, but got a ${$x.dtype} tensor instead.`);\n util.assert(\n rate >= 0 && rate < 1,\n () => `rate must be a float in the range [0, 1), but got ${rate}.`);\n\n if (rate === 0) {\n return x instanceof Tensor ? $x.clone() : $x;\n }\n\n const $noiseShape = getNoiseShape($x, noiseShape);\n const keepProb = 1 - rate;\n const multiplier = div(\n floor(add(randomUniform($noiseShape, 0, 1, 'float32', seed), keepProb)),\n keepProb);\n\n return mul($x, multiplier);\n}\n\nexport const dropout = /* @__PURE__ */ op({dropout_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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_(\n predictions: T|TensorLike, targets: U|TensorLike, k = 1): Promise {\n const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');\n const $targets = convertToTensor(targets, 'targets', 'inTopK');\n\n assert(\n $predictions.rank > 1,\n () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +\n `but got ${$predictions.rank}`);\n assert(\n $predictions.rank - 1 === $targets.rank,\n () => `predictions rank should be 1 larger than ` +\n `targets rank, but got predictions rank ` +\n `${$predictions.rank} and targets rank ${$targets.rank}`);\n assertShapesMatch(\n $predictions.shape.slice(0, $predictions.shape.length - 1),\n $targets.shape,\n `predictions's shape should be align with the targets' shape, ` +\n 'except the last dimension.');\n const lastDim = $predictions.shape[$predictions.shape.length - 1];\n assert(\n k > 0 && k <= lastDim,\n () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +\n `dimension (${lastDim}), but got ${k}`);\n\n const predictionsVals = await $predictions.data();\n const targetsVals = await $targets.data();\n\n // Reshape predictionsVals into a 2d tensor [batch, lastDim]\n // and look up topK along lastDim.\n const [batch, size] = [predictionsVals.length / lastDim, lastDim];\n const precision = getTypedArrayFromDType('bool', batch);\n\n for (let b = 0; b < batch; b++) {\n const offset = b * size;\n const vals = predictionsVals.subarray(offset, offset + size);\n const valAndInd: Array<{value: number, index: number}> = [];\n for (let i = 0; i < vals.length; i++) {\n valAndInd.push({value: vals[i], index: i});\n }\n valAndInd.sort((a, b) => b.value - a.value);\n\n precision[b] = 0;\n for (let i = 0; i < k; i++) {\n if (valAndInd[i].index === targetsVals[b]) {\n precision[b] = 1;\n break;\n }\n }\n }\n\n if (predictions !== $predictions) {\n $predictions.dispose();\n }\n if (targets !== $targets) {\n $targets.dispose();\n }\n\n // Output precision has the same shape as targets.\n return tensor(precision, $targets.shape, 'bool') as U;\n}\n\nexport const inTopKAsync = inTopKAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the filter of a 2D convolution.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n * [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.\n * @param dy The dy image, of rank 4 or rank 3, of shape\n * [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.\n * @param filterShape The shape of the filter, length 4,\n * [filterHeight, filterWidth, inDepth, outDepth].\n * @param strides The strides of the convolution: [strideHeight,\n * strideWidth].\n * @param pad A string from: 'same', 'valid'. The type of padding algorithm\n * used in the forward prop of the op.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction conv2DBackpropFilter_(\n x: T, dy: T, filterShape: [number, number, number, number],\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n let x4D = x as Tensor4D;\n if (x.rank === 3) {\n x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n }\n let dy4D = dy as Tensor4D;\n if (dy4D.rank === 3) {\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +\n `${x4D.shape}.`);\n util.assert(\n dy4D.rank === 4,\n () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +\n `${dy4D.shape}.`);\n util.assert(\n filterShape.length === 4,\n () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +\n `${filterShape}.`);\n const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n util.assert(\n inDepth === filterShape[2],\n () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +\n `match input depth in filter (${filterShape[2]}.`);\n util.assert(\n outDepth === filterShape[3],\n () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +\n `match output depth for filter (${filterShape[3]}).`);\n conv_util.checkPadOnDimRoundingMode('conv2dDerFilter', pad, dimRoundingMode);\n const inputs: Conv2DBackpropFilterInputs = {x: x4D, dy: dy4D};\n const attrs: Conv2DBackpropFilterAttrs =\n {strides, pad, dataFormat, dimRoundingMode, filterShape};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n Conv2DBackpropFilter, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const conv2DBackpropFilter = /* @__PURE__ */ op({conv2DBackpropFilter_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\nimport * as broadcast_util from './broadcast_util';\nimport {elu} from './elu';\nimport {Activation} from './fused_types';\nimport {leakyRelu} from './leaky_relu';\nimport {mul} from './mul';\nimport {prelu} from './prelu';\nimport {relu} from './relu';\nimport {relu6} from './relu6';\nimport {reshape} from './reshape';\nimport {sigmoid} from './sigmoid';\nimport {step} from './step';\nimport {sum} from './sum';\n\n// Returns gradient for fused activation.\nexport function getFusedDyActivation(\n dy: Tensor, y: Tensor, activation: Activation): Tensor {\n if (activation == null || activation === 'linear') {\n return dy;\n }\n if (activation === 'relu') {\n return mul(dy, step(y));\n }\n throw new Error(\n `Cannot compute gradient for fused activation ${activation}.`);\n}\n\n// Returns gradient for fused bias.\nexport function getFusedBiasGradient(\n bias: Tensor, dyActivation: Tensor): Tensor {\n let res = dyActivation;\n const reduceAxes =\n broadcast_util.getReductionAxes(bias.shape, dyActivation.shape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, bias.shape);\n}\n\nexport function applyActivation(\n x: Tensor, activation: Activation, preluActivationWeights?: Tensor,\n leakyreluAlpha?: number): Tensor {\n if (activation === 'linear') {\n return x;\n } else if (activation === 'relu') {\n return relu(x);\n } else if (activation === 'elu') {\n return elu(x);\n } else if (activation === 'relu6') {\n return relu6(x);\n } else if (activation === 'prelu') {\n return prelu(x, preluActivationWeights);\n } else if (activation === 'leakyrelu') {\n return leakyRelu(x, leakyreluAlpha);\n } else if (activation === 'sigmoid') {\n return sigmoid(x);\n }\n throw new Error(`Unknown fused activation ${activation}.`);\n}\n\n// Whether we should call fused ops.\nexport const shouldFuse = (gradientDepth: number, activation: Activation) => {\n const gradientMode = gradientDepth > 0;\n return !gradientMode || activation === 'linear';\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {conv2d as unfusedConv2d} from '../conv2d';\nimport {conv2DBackpropFilter} from '../conv2d_backprop_filter';\nimport {conv2DBackpropInput} from '../conv2d_backprop_input';\nimport * as conv_util from '../conv_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes a 2D convolution over the input x, optionally fused with adding a\n * bias and applying an activation.\n *\n * ```js\n * const inputDepth = 2;\n * const inShape = [2, 2, 2, inputDepth];\n * const outputDepth = 2;\n * const fSize = 1;\n * const pad = 0;\n * const strides = 1;\n *\n * const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n * 16], inShape);\n * const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,\n * outputDepth]);\n *\n * tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',\n * dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();\n * ```\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n * `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid` output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`) to be\n * applied\n * after biasAdd.\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n * of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n * activation.\n */\nfunction fusedConv2d_({\n x,\n filter,\n strides,\n pad,\n dataFormat = 'NHWC',\n dilations = [1, 1],\n dimRoundingMode,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha\n}: {\n x: T|TensorLike,\n filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n bias?: Tensor|TensorLike,\n activation?: Activation,\n preluActivationWeights?: Tensor,\n leakyreluAlpha?: number\n}): T {\n activation = activation || 'linear';\n\n if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n // TODO: Transpose bias and preluActivationWeights properly for NCHW\n // format before computation.\n util.assert(\n dataFormat === 'NHWC',\n () => `Error in fused conv2d: got dataFormat of ${dataFormat} but ` +\n `only NHWC is currently supported for the case of gradient depth ` +\n `is 0 and the activation is not linear.`);\n\n let result = unfusedConv2d(\n x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha) as T;\n }\n\n const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in fused conv2d: input must be rank 4, but got rank ` +\n `${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in fused conv2d: filter must be rank 4, but got rank ` +\n `${$filter.rank}.`);\n conv_util.checkPadOnDimRoundingMode('fused conv2d', pad, dimRoundingMode);\n const inputChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n util.assert(\n $filter.shape[2] === inputChannels,\n () => `Error in conv2d: depth of input (${inputChannels}) must match ` +\n `input depth for filter ${$filter.shape[2]}.`);\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = conv_util.computeConv2DInfo(\n x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);\n\n let $bias: Tensor;\n if (bias != null) {\n $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n [$bias] = makeTypesMatch($bias, $x);\n\n // According to TensorFlow, the bias is supposed be a 1-D tensor or a\n // scalar.\n //\n // 3-D or 4-D bias is not disabled for NHWC format, because they are\n // currently being used in some cases. For examplem in our code base,\n // https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/fused_conv2d_test.ts#L1972.\n if (dataFormat === 'NHWC') {\n broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n } else {\n util.assert(\n $bias.shape.length <= 1,\n () => `Error in fused conv2d: only supports scalar or 1-D Tensor ` +\n `bias for NCHW format but got the bias of ` +\n `rank-${$bias.shape.length}.`);\n\n util.assert(\n $bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels ||\n $bias.shape[0] === 1,\n () => `Error in fused conv2d: bias shape (${$bias.shape}) is not ` +\n `compatible with the number of output channels ` +\n `(${convInfo.outChannels})`);\n }\n }\n\n let $preluActivationWeights: Tensor;\n if (preluActivationWeights != null) {\n // PReLU's activation weights could be a scalar, a 1-D tensor or a 3-D\n // tensor.\n const alphaShape = preluActivationWeights.shape;\n util.assert(\n alphaShape.length <= 1 || alphaShape.length === 3,\n () => `Error in fused conv2d: only supports scalar, 1-D Tensor or ` +\n `3-D Tensor PReLU activation weights but got a tensor of ` +\n `rank-${alphaShape.length}.`);\n\n if (alphaShape.length === 1) {\n // Whether the data format is NCHW or NHWC, the 1-D PReLU activation\n // weights tensor should be aligned with the output channels of conv2d\n // result.\n util.assert(\n alphaShape[0] === 1 || alphaShape[0] === convInfo.outChannels,\n () => `Error in fused conv2d: PReLU activation weights ` +\n `(${alphaShape}) is not compatible with the number of output ` +\n `channels (${convInfo.outChannels}).`);\n } else if (alphaShape.length === 3) {\n // Whether the data format is NCHW or NHWC, the PReLU activation weights\n // tensor should has the compatible shape with the result of conv2d.\n try {\n broadcast_util.assertAndGetBroadcastShape(\n alphaShape, convInfo.outShape);\n } catch (e) {\n const errMsg =\n `Error in fused conv2d: PReLU activation weights (${alphaShape}) ` +\n `is not compatible with the output shape of the conv2d ` +\n `(${convInfo.outShape}).`;\n throw Error(errMsg);\n }\n }\n\n $preluActivationWeights = convertToTensor(\n preluActivationWeights, 'prelu weights', 'fused conv2d');\n }\n\n const grad = (dy: Tensor4D, saved: Tensor[]) => {\n util.assert(\n dataFormat === 'NHWC',\n () => `Error in gradient of fused conv2D: got dataFormat of ${\n dataFormat} but only NHWC is currently supported.`);\n\n const [$filter, x4D, y, $bias] =\n saved as [Tensor4D, Tensor4D, Tensor4D, Tensor];\n\n const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n util.assert(\n conv_util.tupleValuesAreOne(dilations),\n () => 'Error in gradient of fused conv2D: ' +\n `dilation rates greater than 1 ` +\n `are not yet supported in gradients. Got dilations '${dilations}'`);\n\n const xDer =\n conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad);\n const filterDer =\n conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad);\n const der: Tensor[] = [xDer, filterDer];\n\n if ($bias != null) {\n const biasDer = getFusedBiasGradient($bias, dyActivation);\n der.push(biasDer);\n }\n return der;\n };\n\n const inputs: FusedConv2DInputs = {\n x: x4D,\n filter: $filter,\n bias: $bias,\n preluActivationWeights: $preluActivationWeights\n };\n\n const attrs: FusedConv2DAttrs = {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n };\n\n // Depending on the the params passed in we will have different number of\n // inputs and thus a a different number of elements in the gradient.\n if (bias == null) {\n const customOp =\n customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n let res: Tensor4D|Tensor3D =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n FusedConv2D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n\n save([filter, x4D, res]);\n\n if (reshapedTo4D) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n Tensor3D;\n }\n\n return {value: res, gradFunc: grad};\n });\n return customOp(x4D, $filter) as T;\n } else {\n const customOpWithBias = customGrad(\n (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n FusedConv2D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n\n save([filter, x4D, res, bias]);\n\n if (reshapedTo4D) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n Tensor3D;\n }\n\n return {value: res, gradFunc: grad};\n });\n\n return customOpWithBias(x4D, $filter, $bias) as T;\n }\n}\nexport const conv2d = /* @__PURE__ */ op({fusedConv2d_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropFilter_(\n x: T, dy: T, filterShape: [number, number, number, number],\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n let x4D = x as Tensor4D;\n if (x.rank === 3) {\n x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n }\n let dy4D = dy as Tensor4D;\n if (dy4D.rank === 3) {\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n }\n\n const inputs: DepthwiseConv2dNativeBackpropFilterInputs = {x: x4D, dy: dy4D};\n const attrs: DepthwiseConv2dNativeBackpropFilterAttrs =\n {strides, pad, dimRoundingMode, dilations, filterShape};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n DepthwiseConv2dNativeBackpropFilter,\n inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const depthwiseConv2dNativeBackpropFilter =\n op({depthwiseConv2dNativeBackpropFilter_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropInput_(\n xShape: [number, number, number, number], dy: T, filter: Tensor4D,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dilations: [number, number]|number = [1, 1],\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n let dy4D = dy as Tensor4D;\n let reshapedTo4D = false;\n if (dy.rank === 3) {\n reshapedTo4D = true;\n dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n }\n\n const inputs: DepthwiseConv2dNativeBackpropInputInputs = {dy: dy4D, filter};\n const attrs: DepthwiseConv2dNativeBackpropInputAttrs =\n {strides, pad, dimRoundingMode, dilations, inputShape: xShape};\n\n const res =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n DepthwiseConv2dNativeBackpropInput,\n inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const depthwiseConv2dNativeBackpropInput =\n op({depthwiseConv2dNativeBackpropInput_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport * as conv_util from '../conv_util';\nimport {depthwiseConv2d as unfusedDepthwiseConv2d} from '../depthwise_conv2d';\nimport {depthwiseConv2dNativeBackpropFilter} from '../depthwise_conv2d_native_backprop_filter';\nimport {depthwiseConv2dNativeBackpropInput} from '../depthwise_conv2d_native_backprop_input';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes depthwise 2D convolution, optionally fused with adding a\n * bias and applying an activation.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n * https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n * - `same` and stride 1: output will be of same size as input,\n * regardless of filter size.\n * - `valid`: output will be smaller than input if filter is larger\n * than 1x1.\n * - For more info, see this guide:\n * [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n * https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n * in which we sample input values across the height and width dimensions\n * in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n * number, then `dilationHeight == dilationWidth`. If it is greater than\n * 1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n * \"NHWC\". Specify the data format of the input and output data. With the\n * default format \"NHWC\", the data is stored in the order of: [batch,\n * height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`).\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n * of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n * activation.\n */\nfunction fusedDepthwiseConv2d_({\n x,\n filter,\n strides,\n pad,\n dataFormat = 'NHWC',\n dilations = [1, 1],\n dimRoundingMode,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha\n}: {\n x: T|TensorLike,\n filter: Tensor4D|TensorLike,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number,\n dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil',\n bias?: Tensor|TensorLike,\n activation?: Activation,\n preluActivationWeights?: Tensor,\n leakyreluAlpha?: number\n}): T {\n if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n let result = unfusedDepthwiseConv2d(\n x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha) as T;\n }\n\n const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n const $filter =\n convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n let x4D = $x as Tensor4D;\n let reshapedTo4D = false;\n if ($x.rank === 3) {\n reshapedTo4D = true;\n x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n }\n util.assert(\n x4D.rank === 4,\n () => `Error in fused depthwiseConv2d: input must be rank 4, but got ` +\n `rank ${x4D.rank}.`);\n util.assert(\n $filter.rank === 4,\n () => `Error in fused depthwiseConv2d: filter must be rank 4, ` +\n `but got rank ${$filter.rank}.`);\n util.assert(\n x4D.shape[3] === $filter.shape[2],\n () => `Error in fused depthwiseConv2d: number of input channels ` +\n `(${x4D.shape[3]}) must match the inChannels dimension in ` +\n `filter ${$filter.shape[2]}.`);\n if (dilations == null) {\n dilations = [1, 1];\n }\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () =>\n 'Error in fused depthwiseConv2d: Either strides or dilations must ' +\n `be 1. Got strides ${strides} and dilations '${dilations}'`);\n conv_util.checkPadOnDimRoundingMode(\n 'fused depthwiseConv2d', pad, dimRoundingMode);\n const convInfo = conv_util.computeConv2DInfo(\n x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode,\n true /* depthwise */);\n\n let $bias: Tensor;\n if (bias != null) {\n $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n [$bias] = makeTypesMatch($bias, $x);\n\n broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n }\n\n let $preluActivationWeights: Tensor;\n if (preluActivationWeights != null) {\n $preluActivationWeights = convertToTensor(\n preluActivationWeights, 'prelu weights', 'fused depthwiseConv2d');\n }\n\n const grad = (dy: Tensor4D, saved: Tensor[]) => {\n util.assert(\n conv_util.tupleValuesAreOne(dilations),\n () => 'Error in gradient of fused depthwiseConv2d: dilation rates ' +\n `greater than 1 are not yet supported. Got dilations ` +\n `'${dilations}'`);\n const [$filter, x4D, y, bias] = saved;\n\n const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n const xDer = depthwiseConv2dNativeBackpropInput(\n (x4D as Tensor4D).shape, dyActivation, $filter as Tensor4D, strides,\n pad, dilations, dimRoundingMode);\n const filterDer = depthwiseConv2dNativeBackpropFilter(\n x4D as Tensor4D, dyActivation, ($filter as Tensor4D).shape, strides,\n pad, dilations, dimRoundingMode);\n\n if (bias != null) {\n const biasDer = getFusedBiasGradient($bias, dyActivation);\n return [xDer, filterDer, biasDer];\n }\n return [xDer, filterDer];\n };\n\n const inputs: FusedDepthwiseConv2DInputs = {\n x: x4D,\n filter: $filter,\n bias: $bias,\n preluActivationWeights: $preluActivationWeights\n };\n const attrs: FusedDepthwiseConv2DAttrs = {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n };\n\n // Depending on the the params passed in we will have different number of\n // inputs and thus a a different number of elements in the gradient.\n if (bias == null) {\n const customOp =\n customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n FusedDepthwiseConv2D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n\n save([filter, x4D, res]);\n\n if (reshapedTo4D) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n Tensor3D;\n }\n\n return {value: res, gradFunc: grad};\n });\n return customOp(x4D, $filter) as T;\n } else {\n const customOpWithBias = customGrad(\n (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n FusedDepthwiseConv2D, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n\n save([filter, x4D, res, bias]);\n\n if (reshapedTo4D) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n Tensor3D;\n }\n\n return {value: res, gradFunc: grad};\n });\n\n return customOpWithBias(x4D, $filter, $bias) as T;\n }\n}\nexport const depthwiseConv2d = /* @__PURE__ */ op({fusedDepthwiseConv2d_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {matMul as unfusedMatMul} from '../mat_mul';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes the dot product of two matrices with optional activation and bias.\n *\n * ```js\n * const a = tf.tensor2d([-1, -2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const bias = tf.tensor2d([1, 2], [1, 2]);\n *\n * tf.fused.matMul({a, b, bias, activation: 'relu'}).print();\n * ```\n *\n * @param obj An object with the following properties:\n * - `a` First matrix in dot product operation.\n * - `b` Second matrix in dot product operation.\n * - `transposeA` If true, `a` is transposed before multiplication.\n * - `transposeB` If true, `b` is transposed before multiplication.\n * - `bias` Matrix to be added to the result.\n * - `activation` Name of activation kernel (defaults to `linear`).\n * - `preluActivationWeights` Tensor of prelu weights.\n * - `leakyreluAlpha` Alpha of leakyrelu.\n */\nfunction fusedMatMul_({\n a,\n b,\n transposeA = false,\n transposeB = false,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha = 0.2,\n}: {\n a: Tensor|TensorLike,\n b: Tensor|TensorLike,\n transposeA?: boolean,\n transposeB?: boolean,\n bias?: Tensor|TensorLike,\n activation?: Activation,\n preluActivationWeights?: Tensor\n leakyreluAlpha?: number\n}): Tensor {\n if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n let result = unfusedMatMul(a, b, transposeA, transposeB);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha);\n }\n\n let $a = convertToTensor(a, 'a', 'fused matMul');\n let $b = convertToTensor(b, 'b', 'fused matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const innerShapeA =\n transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];\n const innerShapeB =\n transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];\n\n const outerShapeA =\n transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];\n const outerShapeB =\n transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];\n\n const outerDimsA = $a.shape.slice(0, -2);\n const outerDimsB = $b.shape.slice(0, -2);\n const batchDimA = util.sizeFromShape(outerDimsA);\n const batchDimB = util.sizeFromShape(outerDimsB);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in fused matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n $a.shape.slice(0, -2), $b.shape.slice(0, -2));\n const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n const a3D: Tensor3D = transposeA ?\n reshape($a, [batchDimA, innerShapeA, outerShapeA]) :\n reshape($a, [batchDimA, outerShapeA, innerShapeA]);\n const b3D: Tensor3D = transposeB ?\n reshape($b, [batchDimB, outerShapeB, innerShapeB]) :\n reshape($b, [batchDimB, innerShapeB, outerShapeB]);\n\n let $bias: Tensor;\n if (bias != null) {\n $bias = convertToTensor(bias, 'bias', 'fused matMul');\n [$bias] = makeTypesMatch($bias, $a);\n\n broadcast_util.assertAndGetBroadcastShape(outShape, $bias.shape);\n }\n\n let $preluActivationWeights: Tensor;\n if (preluActivationWeights != null) {\n $preluActivationWeights = convertToTensor(\n preluActivationWeights, 'prelu weights', 'fused matMul');\n }\n\n const grad = (dy: Tensor3D, saved: Tensor[]) => {\n const [a3D, b3D, y, $bias] = saved;\n // we reshape dy because the result of the forward is not\n // necessarily going to be a 3d tensor due to a reshape done at the end of\n // the customOp.\n const dyActivation =\n getFusedDyActivation(reshape(dy, y.shape), y, activation);\n let aDer: Tensor;\n let bDer: Tensor;\n\n if (!transposeA && !transposeB) {\n aDer = unfusedMatMul(dyActivation, b3D, false, true);\n bDer = unfusedMatMul(a3D, dyActivation, true, false);\n } else if (!transposeA && transposeB) {\n aDer = unfusedMatMul(dyActivation, b3D, false, false);\n bDer = unfusedMatMul(dyActivation, a3D, true, false);\n } else if (transposeA && !transposeB) {\n aDer = unfusedMatMul(b3D, dyActivation, false, true);\n bDer = unfusedMatMul(a3D, dyActivation, false, false);\n } else {\n aDer = unfusedMatMul(b3D, dyActivation, true, true);\n bDer = unfusedMatMul(dyActivation, a3D, true, true);\n }\n\n if (bias != null) {\n const biasDer = getFusedBiasGradient($bias, dyActivation);\n return [aDer, bDer, biasDer];\n } else {\n return [aDer, bDer];\n }\n };\n\n const inputs: _FusedMatMulInputs = {\n a: a3D,\n b: b3D,\n bias: $bias,\n preluActivationWeights: $preluActivationWeights\n };\n const attrs: _FusedMatMulAttrs =\n {transposeA, transposeB, activation, leakyreluAlpha};\n\n // Depending on the the params passed in we will have different number of\n // inputs and thus a a different number of elements in the gradient.\n if (bias == null) {\n const customOp =\n customGrad((a3D: Tensor3D, b3D: Tensor3D, save: GradSaveFunc) => {\n const res =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n _FusedMatMul, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor;\n\n save([a3D, b3D, res]);\n\n return {value: reshape(res, outShape), gradFunc: grad};\n });\n return customOp(a3D, b3D);\n } else {\n const customOpWithBias = customGrad(\n (a3D: Tensor3D, b3D: Tensor3D, $bias: Tensor, save: GradSaveFunc) => {\n const res =\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n _FusedMatMul, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor;\n\n save([a3D, b3D, res, $bias]);\n\n return {value: reshape(res, outShape), gradFunc: grad};\n });\n\n return customOpWithBias(a3D, b3D, $bias);\n }\n }\n\n export const matMul = /* @__PURE__ */ op({fusedMatMul_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../../tensor';\nimport {op} from '../operation';\nimport {cosineWindow} from '../signal_ops_util';\n\n/**\n * Generate a hamming window.\n *\n * See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows\n *\n * ```js\n * tf.signal.hammingWindow(10).print();\n * ```\n * @param The length of window\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction hammingWindow_(windowLength: number): Tensor1D {\n return cosineWindow(windowLength, 0.54, 0.46);\n}\nexport const hammingWindow = /* @__PURE__ */ op({hammingWindow_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../../tensor';\nimport {op} from '../operation';\nimport {cosineWindow} from '../signal_ops_util';\n\n/**\n * Generate a Hann window.\n *\n * See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows\n *\n * ```js\n * tf.signal.hannWindow(10).print();\n * ```\n * @param The length of window\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction hannWindow_(windowLength: number): Tensor1D {\n return cosineWindow(windowLength, 0.5, 0.5);\n}\n\nexport const hannWindow = /* @__PURE__ */ op({hannWindow_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {concat} from '../concat';\nimport {fill} from '../fill';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {tensor2d} from '../tensor2d';\n\n/**\n * Expands input into frames of frameLength.\n * Slides a window size with frameStep.\n *\n * ```js\n * tf.signal.frame([1, 2, 3], 2, 1).print();\n * ```\n * @param signal The input tensor to be expanded\n * @param frameLength Length of each frame\n * @param frameStep The frame hop size in samples.\n * @param padEnd Whether to pad the end of signal with padValue.\n * @param padValue A number to use where the input signal does\n * not exist when padEnd is True.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction frame_(\n signal: Tensor1D, frameLength: number, frameStep: number, padEnd = false,\n padValue = 0): Tensor {\n let start = 0;\n const output: Tensor[] = [];\n while (start + frameLength <= signal.size) {\n output.push(slice(signal, start, frameLength));\n start += frameStep;\n }\n\n if (padEnd) {\n while (start < signal.size) {\n const padLen = (start + frameLength) - signal.size;\n const pad = concat([\n slice(signal, start, frameLength - padLen), fill([padLen], padValue)\n ]);\n output.push(pad);\n start += frameStep;\n }\n }\n\n if (output.length === 0) {\n return tensor2d([], [0, frameLength]);\n }\n\n return reshape(concat(output), [output.length, frameLength]);\n}\nexport const frame = /* @__PURE__ */ op({frame_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {enclosingPowerOfTwo} from '../signal_ops_util';\nimport {rfft} from '../spectral/rfft';\n\nimport {frame} from './frame';\nimport {hannWindow} from './hann_window';\n\n/**\n * Computes the Short-time Fourier Transform of signals\n * See: https://en.wikipedia.org/wiki/Short-time_Fourier_transform\n *\n * ```js\n * const input = tf.tensor1d([1, 1, 1, 1, 1])\n * tf.signal.stft(input, 3, 1).print();\n * ```\n * @param signal 1-dimensional real value tensor.\n * @param frameLength The window length of samples.\n * @param frameStep The number of samples to step.\n * @param fftLength The size of the FFT to apply.\n * @param windowFn A callable that takes a window length and returns 1-d tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction stft_(\n signal: Tensor1D, frameLength: number, frameStep: number,\n fftLength?: number,\n windowFn: (length: number) => Tensor1D = hannWindow): Tensor {\n if (fftLength == null) {\n fftLength = enclosingPowerOfTwo(frameLength);\n }\n const framedSignal = frame(signal, frameLength, frameStep);\n const windowedSignal = mul(framedSignal, windowFn(frameLength));\n return rfft(windowedSignal, fftLength);\n}\nexport const stft = /* @__PURE__ */ op({stft_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor1D, Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Extracts crops from the input image tensor and resizes them using bilinear\n * sampling or nearest neighbor sampling (possibly with aspect ratio change)\n * to a common output size specified by cropSize.\n *\n * @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,\n * where imageHeight and imageWidth must be positive, specifying the\n * batch of images from which to take crops\n * @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized\n * coordinates of the box in the `boxInd[i]`th image in the batch\n * @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range\n * `[0, batch)` that specifies the image that the `i`-th box refers to.\n * @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`\n * specifying the size to which all crops are resized to.\n * @param method Optional string from `'bilinear' | 'nearest'`,\n * defaults to bilinear, which specifies the sampling method for resizing\n * @param extrapolationValue A threshold for deciding when to remove boxes based\n * on score. Defaults to 0.\n * @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction cropAndResize_(\n image: Tensor4D|TensorLike,\n boxes: Tensor2D|TensorLike,\n boxInd: Tensor1D|TensorLike,\n cropSize: [number, number],\n method: 'bilinear'|'nearest' = 'bilinear',\n extrapolationValue = 0,\n ): Tensor4D {\n const $image = convertToTensor(image, 'image', 'cropAndResize');\n const $boxes = convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');\n const $boxInd = convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');\n\n const numBoxes = $boxes.shape[0];\n\n util.assert(\n $image.rank === 4,\n () => 'Error in cropAndResize: image must be rank 4,' +\n `but got rank ${$image.rank}.`);\n util.assert(\n $boxes.rank === 2 && $boxes.shape[1] === 4,\n () => `Error in cropAndResize: boxes must be have size [${numBoxes},4] ` +\n `but had shape ${$boxes.shape}.`);\n util.assert(\n $boxInd.rank === 1 && $boxInd.shape[0] === numBoxes,\n () => `Error in cropAndResize: boxInd must be have size [${numBoxes}] ` +\n `but had shape ${$boxes.shape}.`);\n util.assert(\n cropSize.length === 2,\n () => `Error in cropAndResize: cropSize must be of length 2, but got ` +\n `length ${cropSize.length}.`);\n util.assert(\n cropSize[0] >= 1 && cropSize[1] >= 1,\n () => `cropSize must be atleast [1,1], but was ${cropSize}`);\n util.assert(\n method === 'bilinear' || method === 'nearest',\n () => `method must be bilinear or nearest, but was ${method}`);\n\n const inputs:\n CropAndResizeInputs = {image: $image, boxes: $boxes, boxInd: $boxInd};\n const attrs: CropAndResizeAttrs = {method, extrapolationValue, cropSize};\n const res = ENGINE.runKernel(\n CropAndResize, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n return res as Tensor4D;\n}\n\nexport const cropAndResize = /* @__PURE__ */ op({cropAndResize_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FlipLeftRight, FlipLeftRightInputs} from '../../kernel_names';\nimport {Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {op} from '../operation';\n\n/**\n * Flips the image left to right. Currently available in the CPU, WebGL, and\n * WASM backends.\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n */\n/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */\nfunction flipLeftRight_(image: Tensor4D|TensorLike): Tensor4D {\n const $image = convertToTensor(image, 'image', 'flipLeftRight', 'float32');\n\n util.assert(\n $image.rank === 4,\n () => 'Error in flipLeftRight: image must be rank 4,' +\n `but got rank ${$image.rank}.`);\n\n const inputs: FlipLeftRightInputs = {image: $image};\n const res =\n ENGINE.runKernel(FlipLeftRight, inputs as unknown as NamedTensorMap, {});\n return res as Tensor4D;\n}\n\nexport const flipLeftRight = /* @__PURE__ */ op({flipLeftRight_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {tile} from '../tile';\n\n/**\n * Converts images from grayscale to RGB format.\n *\n * @param image A grayscale tensor to convert. The `image`'s last dimension must\n * be size 1 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction grayscaleToRGB_(image: T|TensorLike): T {\n const $image = convertToTensor(image, 'image', 'grayscaleToRGB');\n\n const lastDimsIdx = $image.rank - 1;\n const lastDims = $image.shape[lastDimsIdx];\n\n util.assert(\n $image.rank >= 2,\n () => 'Error in grayscaleToRGB: images must be at least rank 2, ' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n lastDims === 1,\n () => 'Error in grayscaleToRGB: last dimension of a grayscale image ' +\n `should be size 1, but got size ${lastDims}.`);\n\n const reps = new Array($image.rank);\n\n reps.fill(1, 0, lastDimsIdx);\n reps[lastDimsIdx] = 3;\n\n return tile($image, reps);\n}\n\nexport const grayscaleToRGB = /* @__PURE__ */ op({grayscaleToRGB_});\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {cast} from '../cast';\nimport {einsum} from '../einsum';\nimport {expandDims} from '../expand_dims';\nimport {op} from '../operation';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Converts images from RGB format to grayscale.\n *\n * @param image A RGB tensor to convert. The `image`'s last dimension must\n * be size 3 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction rgbToGrayscale_(image: T|TensorLike): T {\n const $image = convertToTensor(image, 'image', 'RGBToGrayscale');\n\n const lastDimsIdx = $image.rank - 1;\n const lastDims = $image.shape[lastDimsIdx];\n\n util.assert(\n $image.rank >= 2,\n () => 'Error in RGBToGrayscale: images must be at least rank 2, ' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n lastDims === 3,\n () => 'Error in RGBToGrayscale: last dimension of an RGB image ' +\n `should be size 3, but got size ${lastDims}.`);\n\n // Remember original dtype so we can convert back if needed\n const origDtype = $image.dtype;\n const fltImage = cast($image, 'float32');\n\n const rgbWeights = tensor1d([0.2989, 0.5870, 0.1140]);\n\n let grayFloat;\n switch ($image.rank) {\n case 2:\n grayFloat = einsum('ij,j->i', fltImage, rgbWeights);\n break;\n case 3:\n grayFloat = einsum('ijk,k->ij', fltImage, rgbWeights);\n break;\n case 4:\n grayFloat = einsum('ijkl,l->ijk', fltImage, rgbWeights);\n break;\n case 5:\n grayFloat = einsum('ijklm,m->ijkl', fltImage, rgbWeights);\n break;\n case 6:\n grayFloat = einsum('ijklmn,n->ijklm', fltImage, rgbWeights);\n break;\n default:\n throw new Error('Not a valid tensor rank.');\n }\n grayFloat = expandDims(grayFloat, -1);\n\n return cast(grayFloat, origDtype) as T;\n}\n\nexport const rgbToGrayscale = /* @__PURE__ */ op({rgbToGrayscale_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Rotates the input image tensor counter-clockwise with an optional offset\n * center of rotation. Currently available in the CPU, WebGL, and WASM backends.\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param radians The amount of rotation.\n * @param fillValue The value to fill in the empty space leftover\n * after rotation. Can be either a single grayscale value (0-255), or an\n * array of three numbers `[red, green, blue]` specifying the red, green,\n * and blue channels. Defaults to `0` (black).\n * @param center The center of rotation. Can be either a single value (0-1), or\n * an array of two numbers `[centerX, centerY]`. Defaults to `0.5` (rotates\n * the image around its center).\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction rotateWithOffset_(\n image: Tensor4D|TensorLike, radians: number,\n fillValue: number|[number, number, number] = 0,\n center: number|[number, number] = 0.5): Tensor4D {\n const $image = convertToTensor(image, 'image', 'rotateWithOffset', 'float32');\n\n util.assert(\n $image.rank === 4,\n () => 'Error in rotateWithOffset: image must be rank 4,' +\n `but got rank ${$image.rank}.`);\n\n const inputs: RotateWithOffsetInputs = {image: $image};\n const attrs: RotateWithOffsetAttrs = {radians, fillValue, center};\n const res = ENGINE.runKernel(\n RotateWithOffset, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n return res as Tensor4D;\n}\n\nexport const rotateWithOffset = /* @__PURE__ */ op({rotateWithOffset_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport * as util from '../util';\n\nfunction nonMaxSuppSanityCheck(\n boxes: Tensor2D, scores: Tensor1D, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number, softNmsSigma?: number): {\n maxOutputSize: number,\n iouThreshold: number,\n scoreThreshold: number,\n softNmsSigma: number\n} {\n if (iouThreshold == null) {\n iouThreshold = 0.5;\n }\n if (scoreThreshold == null) {\n scoreThreshold = Number.NEGATIVE_INFINITY;\n }\n if (softNmsSigma == null) {\n softNmsSigma = 0.0;\n }\n\n const numBoxes = boxes.shape[0];\n maxOutputSize = Math.min(maxOutputSize, numBoxes);\n\n util.assert(\n 0 <= iouThreshold && iouThreshold <= 1,\n () => `iouThreshold must be in [0, 1], but was '${iouThreshold}'`);\n util.assert(\n boxes.rank === 2,\n () => `boxes must be a 2D tensor, but was of rank '${boxes.rank}'`);\n util.assert(\n boxes.shape[1] === 4,\n () =>\n `boxes must have 4 columns, but 2nd dimension was ${boxes.shape[1]}`);\n util.assert(scores.rank === 1, () => 'scores must be a 1D tensor');\n util.assert(\n scores.shape[0] === numBoxes,\n () => `scores has incompatible shape with boxes. Expected ${numBoxes}, ` +\n `but was ${scores.shape[0]}`);\n util.assert(\n 0 <= softNmsSigma && softNmsSigma <= 1,\n () => `softNmsSigma must be in [0, 1], but was '${softNmsSigma}'`);\n return {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n}\n\nexport {nonMaxSuppSanityCheck};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV3} from '../../kernel_names';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppression_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY): Tensor1D {\n const $boxes =\n convertToTensor(boxes, 'boxes', 'nonMaxSuppression', 'float32');\n const $scores =\n convertToTensor(scores, 'scores', 'nonMaxSuppression', 'float32');\n\n const inputs = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n maxOutputSize = inputs.maxOutputSize;\n iouThreshold = inputs.iouThreshold;\n scoreThreshold = inputs.scoreThreshold;\n\n const attrs = {maxOutputSize, iouThreshold, scoreThreshold};\n return ENGINE.runKernel(\n NonMaxSuppressionV3, {boxes: $boxes, scores: $scores}, attrs);\n}\n\nexport const nonMaxSuppression = /* @__PURE__ */ op({nonMaxSuppression_});\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Inserts a value into a sorted array. This method allows duplicate, meaning it\n * allows inserting duplicate value, in which case, the element will be inserted\n * at the lowest index of the value.\n * @param arr The array to modify.\n * @param element The element to insert.\n * @param comparator Optional. If no comparator is specified, elements are\n * compared using array_util.defaultComparator, which is suitable for Strings\n * and Numbers in ascending arrays. If the array contains multiple instances of\n * the target value, the left-most instance will be returned. To provide a\n * comparator, it should take 2 arguments to compare and return a negative,\n * zero, or a positive number.\n */\nexport function binaryInsert(\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(\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(a: T, b: T): number {\n return a > b ? 1 : a < b ? -1 : 0;\n}\n\nfunction binarySearch_(\n arr: T[], target: T, comparator: (a: T, b: T) => number) {\n let left = 0;\n let right = arr.length;\n let middle = 0;\n let found = false;\n while (left < right) {\n middle = left + ((right - left) >>> 1);\n const compareResult = comparator(target, arr[middle]);\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // If compareResult is 0, the value is found. We record it is found,\n // and then keep looking because there may be duplicate.\n found = !compareResult;\n }\n }\n\n return found ? left : -left - 1;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray} from '../types';\nimport {binaryInsert} from './non_max_suppression_util';\n\n/**\n * Implementation of the NonMaxSuppression kernel shared between webgl and cpu.\n */\ninterface Candidate {\n score: number;\n boxIndex: number;\n suppressBeginIndex: number;\n}\n\ninterface NonMaxSuppressionResult {\n selectedIndices: number[];\n selectedScores?: number[];\n validOutputs?: number;\n}\n\nexport function nonMaxSuppressionV3Impl(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number): NonMaxSuppressionResult {\n return nonMaxSuppressionImpl_(\n boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n 0 /* softNmsSigma */);\n}\n\nexport function nonMaxSuppressionV4Impl(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number,\n padToMaxOutputSize: boolean): NonMaxSuppressionResult {\n return nonMaxSuppressionImpl_(\n boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n 0 /* softNmsSigma */, false /* returnScoresTensor */,\n padToMaxOutputSize /* padToMaxOutputSize */, true\n /* returnValidOutputs */);\n}\n\nexport function nonMaxSuppressionV5Impl(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number,\n softNmsSigma: number): NonMaxSuppressionResult {\n return nonMaxSuppressionImpl_(\n boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma,\n true /* returnScoresTensor */);\n}\n\nfunction nonMaxSuppressionImpl_(\n boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number, softNmsSigma: number,\n returnScoresTensor = false, padToMaxOutputSize = false,\n returnValidOutputs = false): NonMaxSuppressionResult {\n // The list is sorted in ascending order, so that we can always pop the\n // candidate with the largest score in O(1) time.\n const candidates = [];\n\n for (let i = 0; i < scores.length; i++) {\n if (scores[i] > scoreThreshold) {\n candidates.push({score: scores[i], boxIndex: i, suppressBeginIndex: 0});\n }\n }\n\n candidates.sort(ascendingComparator);\n\n // If softNmsSigma is 0, the outcome of this algorithm is exactly same as\n // before.\n const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;\n\n const selectedIndices: number[] = [];\n const selectedScores: number[] = [];\n\n while (selectedIndices.length < maxOutputSize && candidates.length > 0) {\n const candidate = candidates.pop();\n const {score: originalScore, boxIndex, suppressBeginIndex} = candidate;\n\n if (originalScore < scoreThreshold) {\n break;\n }\n\n // Overlapping boxes are likely to have similar scores, therefore we\n // iterate through the previously selected boxes backwards in order to\n // see if candidate's score should be suppressed. We use\n // suppressBeginIndex to track and ensure a candidate can be suppressed\n // by a selected box no more than once. Also, if the overlap exceeds\n // iouThreshold, we simply ignore the candidate.\n let ignoreCandidate = false;\n for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {\n const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);\n\n if (iou >= iouThreshold) {\n ignoreCandidate = true;\n break;\n }\n\n candidate.score =\n candidate.score * suppressWeight(iouThreshold, scale, iou);\n\n if (candidate.score <= scoreThreshold) {\n break;\n }\n }\n\n // At this point, if `candidate.score` has not dropped below\n // `scoreThreshold`, then we know that we went through all of the\n // previous selections and can safely update `suppressBeginIndex` to the\n // end of the selected array. Then we can re-insert the candidate with\n // the updated score and suppressBeginIndex back in the candidate list.\n // If on the other hand, `candidate.score` has dropped below the score\n // threshold, we will not add it back to the candidates list.\n candidate.suppressBeginIndex = selectedIndices.length;\n\n if (!ignoreCandidate) {\n // Candidate has passed all the tests, and is not suppressed, so\n // select the candidate.\n if (candidate.score === originalScore) {\n selectedIndices.push(boxIndex);\n selectedScores.push(candidate.score);\n } else if (candidate.score > scoreThreshold) {\n // Candidate's score is suppressed but is still high enough to be\n // considered, so add back to the candidates list.\n binaryInsert(candidates, candidate, ascendingComparator);\n }\n }\n }\n\n // NonMaxSuppressionV4 feature: padding output to maxOutputSize.\n const validOutputs = selectedIndices.length;\n const elemsToPad = maxOutputSize - validOutputs;\n\n if (padToMaxOutputSize && elemsToPad > 0) {\n selectedIndices.push(...new Array(elemsToPad).fill(0));\n selectedScores.push(...new Array(elemsToPad).fill(0.0));\n }\n\n const result: NonMaxSuppressionResult = {selectedIndices};\n\n if (returnScoresTensor) {\n result['selectedScores'] = selectedScores;\n }\n\n if (returnValidOutputs) {\n result['validOutputs'] = validOutputs;\n }\n\n return result;\n}\n\nfunction intersectionOverUnion(boxes: TypedArray, i: number, j: number) {\n const iCoord = boxes.subarray(i * 4, i * 4 + 4);\n const jCoord = boxes.subarray(j * 4, j * 4 + 4);\n const yminI = Math.min(iCoord[0], iCoord[2]);\n const xminI = Math.min(iCoord[1], iCoord[3]);\n const ymaxI = Math.max(iCoord[0], iCoord[2]);\n const xmaxI = Math.max(iCoord[1], iCoord[3]);\n const yminJ = Math.min(jCoord[0], jCoord[2]);\n const xminJ = Math.min(jCoord[1], jCoord[3]);\n const ymaxJ = Math.max(jCoord[0], jCoord[2]);\n const xmaxJ = Math.max(jCoord[1], jCoord[3]);\n const areaI = (ymaxI - yminI) * (xmaxI - xminI);\n const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);\n if (areaI <= 0 || areaJ <= 0) {\n return 0.0;\n }\n const intersectionYmin = Math.max(yminI, yminJ);\n const intersectionXmin = Math.max(xminI, xminJ);\n const intersectionYmax = Math.min(ymaxI, ymaxJ);\n const intersectionXmax = Math.min(xmaxI, xmaxJ);\n const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *\n Math.max(intersectionXmax - intersectionXmin, 0.0);\n return intersectionArea / (areaI + areaJ - intersectionArea);\n}\n\n// A Gaussian penalty function, this method always returns values in [0, 1].\n// The weight is a function of similarity, the more overlap two boxes are, the\n// smaller the weight is, meaning highly overlapping boxe will be significantly\n// penalized. On the other hand, a non-overlapping box will not be penalized.\nfunction suppressWeight(iouThreshold: number, scale: number, iou: number) {\n const weight = Math.exp(scale * iou * iou);\n return iou <= iouThreshold ? weight : 0.0;\n}\n\nfunction ascendingComparator(c1: Candidate, c2: Candidate) {\n // For objects with same scores, we make the object with the larger index go\n // first. In an array that pops from the end, this means that the object with\n // the smaller index will be popped first. This ensures the same output as\n // the TensorFlow python version.\n return (c1.score - c2.score) ||\n ((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {nonMaxSuppressionV3Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This is the async version of `nonMaxSuppression`\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionAsync_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY): Promise {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n const inputs = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n maxOutputSize = inputs.maxOutputSize;\n iouThreshold = inputs.iouThreshold;\n scoreThreshold = inputs.scoreThreshold;\n\n const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n const boxesVals = boxesAndScores[0];\n const scoresVals = boxesAndScores[1];\n\n // We call a cpu based impl directly with the typedarray data here rather\n // than a kernel because all kernels are synchronous (and thus cannot await\n // .data()).\n const {selectedIndices} = nonMaxSuppressionV3Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n if ($boxes !== boxes) {\n $boxes.dispose();\n }\n if ($scores !== scores) {\n $scores.dispose();\n }\n\n return tensor1d(selectedIndices, 'int32');\n}\n\nexport const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n * When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - selectedScores: A 1D tensor with the corresponding scores for each\n * selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionWithScore_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n softNmsSigma = 0.0): NamedTensorMap {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n maxOutputSize = params.maxOutputSize;\n iouThreshold = params.iouThreshold;\n scoreThreshold = params.scoreThreshold;\n softNmsSigma = params.softNmsSigma;\n\n const inputs: NonMaxSuppressionV5Inputs = {boxes: $boxes, scores: $scores};\n const attrs: NonMaxSuppressionV5Attrs =\n {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const result = ENGINE.runKernel(\n NonMaxSuppressionV5, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor[];\n\n return {selectedIndices: result[0], selectedScores: result[1]};\n}\n\nexport const nonMaxSuppressionWithScore = /* @__PURE__ */ op({nonMaxSuppressionWithScore_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {nonMaxSuppressionV5Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n * When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - selectedScores: A 1D tensor with the corresponding scores for each\n * selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionWithScoreAsync_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n softNmsSigma = 0.0): Promise {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n maxOutputSize = params.maxOutputSize;\n iouThreshold = params.iouThreshold;\n scoreThreshold = params.scoreThreshold;\n softNmsSigma = params.softNmsSigma;\n\n const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n const boxesVals = boxesAndScores[0];\n const scoresVals = boxesAndScores[1];\n\n // We call a cpu based impl directly with the typedarray data here rather\n // than a kernel because all kernels are synchronous (and thus cannot await\n // .data()).\n const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n\n if ($boxes !== boxes) {\n $boxes.dispose();\n }\n if ($scores !== scores) {\n $scores.dispose();\n }\n\n return {\n selectedIndices: tensor1d(selectedIndices, 'int32'),\n selectedScores: tensor1d(selectedScores)\n };\n}\n\nexport const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n * `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - validOutputs: A scalar denoting how many elements in `selectedIndices`\n * are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionPadded_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n padToMaxOutputSize = false): NamedTensorMap {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n null /* softNmsSigma */);\n const $maxOutputSize = params.maxOutputSize;\n const $iouThreshold = params.iouThreshold;\n const $scoreThreshold = params.scoreThreshold;\n\n const inputs: NonMaxSuppressionV4Inputs = {boxes: $boxes, scores: $scores};\n const attrs: NonMaxSuppressionV4Attrs = {\n maxOutputSize: $maxOutputSize,\n iouThreshold: $iouThreshold,\n scoreThreshold: $scoreThreshold,\n padToMaxOutputSize\n };\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const result = ENGINE.runKernel(\n NonMaxSuppressionV4, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor[];\n\n return {selectedIndices: result[0], validOutputs: result[1]};\n}\n\nexport const nonMaxSuppressionPadded = /* @__PURE__ */ op({nonMaxSuppressionPadded_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {nonMaxSuppressionV4Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {scalar} from '../scalar';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n * the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n * boxes overlap too much with respect to IOU. Must be between [0, 1].\n * Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n * on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n * `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n * - selectedIndices: A 1D tensor with the selected box indices.\n * - validOutputs: A scalar denoting how many elements in `selectedIndices`\n * are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionPaddedAsync_(\n boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n maxOutputSize: number, iouThreshold = 0.5,\n scoreThreshold = Number.NEGATIVE_INFINITY,\n padToMaxOutputSize = false): Promise {\n const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n const params = nonMaxSuppSanityCheck(\n $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n null /* softNmsSigma */);\n const $maxOutputSize = params.maxOutputSize;\n const $iouThreshold = params.iouThreshold;\n const $scoreThreshold = params.scoreThreshold;\n\n const [boxesVals, scoresVals] =\n await Promise.all([$boxes.data(), $scores.data()]);\n\n // We call a cpu based impl directly with the typedarray data here rather\n // than a kernel because all kernels are synchronous (and thus cannot await\n // .data()).\n const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold,\n padToMaxOutputSize);\n\n if ($boxes !== boxes) {\n $boxes.dispose();\n }\n if ($scores !== scores) {\n $scores.dispose();\n }\n\n return {\n selectedIndices: tensor1d(selectedIndices, 'int32'),\n validOutputs: scalar(validOutputs, 'int32')\n };\n}\n\nexport const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Bilinear resize a single 3D image or a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n * images to. Each channel is resized individually.\n * @param alignCorners Defaults to `false`. If true, rescale\n * input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n * corners of images and resized images. If false, rescale by\n * `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers\n * are at 0.5, which would make the floating point coordinates of the top\n * left pixel 0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeBilinear_(\n images: T|TensorLike, size: [number, number], alignCorners = false,\n halfPixelCenters = false): T {\n const $images = convertToTensor(images, 'images', 'resizeBilinear');\n\n util.assert(\n $images.rank === 3 || $images.rank === 4,\n () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +\n `rank ${$images.rank}.`);\n util.assert(\n size.length === 2,\n () => `Error in resizeBilinear: new shape must 2D, but got shape ` +\n `${size}.`);\n util.assert(\n halfPixelCenters === false || alignCorners === false,\n () => `Error in resizeBilinear: If halfPixelCenters is true, ` +\n `alignCorners must be false.`);\n\n let batchImages = $images as Tensor4D;\n let reshapedTo4D = false;\n if ($images.rank === 3) {\n reshapedTo4D = true;\n batchImages = reshape(\n $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n }\n\n const [] = size;\n\n const inputs: ResizeBilinearInputs = {images: batchImages};\n const attrs: ResizeBilinearAttrs = {alignCorners, halfPixelCenters, size};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n ResizeBilinear, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const resizeBilinear = /* @__PURE__ */ op({resizeBilinear_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * NearestNeighbor resize a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n * images to. Each channel is resized individually.\n * @param alignCorners Defaults to False. If true, rescale\n * input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n * corners of images and resized images. If false, rescale by\n * `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixels are of\n * half the actual dimensions, and yield more accurate resizes. This flag\n * would also make the floating point coordinates of the top left pixel\n * 0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeNearestNeighbor_(\n images: T|TensorLike, size: [number, number], alignCorners = false,\n halfPixelCenters = false): T {\n const $images = convertToTensor(images, 'images', 'resizeNearestNeighbor');\n\n util.assert(\n $images.rank === 3 || $images.rank === 4,\n () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +\n `rank ${$images.rank}.`);\n util.assert(\n size.length === 2,\n () =>\n `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +\n `${size}.`);\n util.assert(\n $images.dtype === 'float32' || $images.dtype === 'int32',\n () => '`images` must have `int32` or `float32` as dtype');\n util.assert(\n halfPixelCenters === false || alignCorners === false,\n () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +\n `alignCorners must be false.`);\n let batchImages = $images as Tensor4D;\n let reshapedTo4D = false;\n if ($images.rank === 3) {\n reshapedTo4D = true;\n batchImages = reshape(\n $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n }\n const [] = size;\n\n const inputs: ResizeNearestNeighborInputs = {images: batchImages};\n const attrs:\n ResizeNearestNeighborAttrs = {alignCorners, halfPixelCenters, size};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n ResizeNearestNeighbor, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const resizeNearestNeighbor = /* @__PURE__ */ op({resizeNearestNeighbor_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { Tensor1D, Tensor3D } from '../../tensor';\nimport { tensor1d } from '../tensor1d';\nimport { TensorLike } from '../../types';\nimport { op } from '../operation';\nimport { cast } from '../cast';\nimport { split } from '../split';\nimport { bincount } from '../bincount';\nimport { lessEqual } from '../less_equal';\nimport { greater } from '../greater';\nimport { sum } from '../sum';\nimport { add } from '../add';\nimport { mul } from '../mul';\nimport { div } from '../div';\nimport { sub } from '../sub';\nimport { round } from '../round';\nimport { where } from '../where';\nimport { fill } from '../fill';\nimport {slice} from '../slice';\nimport { range } from '../range';\nimport { tensor } from '../tensor';\nimport * as util from '../../util';\nimport { convertToTensor } from '../../tensor_util_env';\n\n/**\n * Performs image binarization with corresponding threshold\n * (depends on the method)value, which creates a binary image from a grayscale.\n * @param image 3d tensor of shape [imageHeight,imageWidth, depth],\n * where imageHeight and imageWidth must be positive.The image color\n * range should be [0, 255].\n * @param method Optional string from `'binary' | 'otsu'`\n * which specifies the method for thresholding. Defaults to 'binary'.\n * @param inverted Optional boolean whichspecifies\n * if colours should be inverted. Defaults to false.\n * @param threshValue Optional number which defines threshold value from 0 to 1.\n * Defaults to 0.5.\n * @return A 3d tensor of shape [imageHeight,imageWidth, depth], which\n * contains binarized image.\n */\n\nfunction threshold_(\n image: Tensor3D | TensorLike,\n method = 'binary',\n inverted = false,\n threshValue = 0.5\n): Tensor3D {\n const $image = convertToTensor(image, 'image', 'threshold');\n\n /* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.\n\tReference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29 */\n\n const RED_INTENCITY_COEF = 0.2989;\n const GREEN_INTENCITY_COEF = 0.5870;\n const BLUE_INTENCITY_COEF = 0.1140;\n const totalPixelsInImage = $image.shape[0] * $image.shape[1];\n\n let $threshold = mul(tensor1d([threshValue]), 255);\n let r, g, b, grayscale;\n\n util.assert(\n $image.rank === 3,\n () => 'Error in threshold: image must be rank 3,' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n $image.shape[2] === 3 || $image.shape[2]=== 1,\n () => 'Error in threshold: ' +\n 'image color channel must be equal to 3 or 1' +\n `but got ${$image.shape[2]}.`);\n\n util.assert(\n $image.dtype === 'int32' || $image.dtype === 'float32',\n () => 'Error in dtype: image dtype must be int32 or float32,' +\n `but got dtype ${$image.dtype}.`);\n\n util.assert(\n method === 'otsu' || method === 'binary',\n () => `Method must be binary or otsu, but was ${method}`);\n\n if ($image.shape[2] === 3) {\n [r, g, b] = split($image, [1, 1, 1], -1);\n const $r = mul(r,RED_INTENCITY_COEF);\n const $g = mul(g,GREEN_INTENCITY_COEF);\n const $b = mul(b,BLUE_INTENCITY_COEF);\n grayscale = add(add($r, $g), $b);\n } else {\n grayscale = image;\n }\n\n if (method === 'otsu') {\n const $histogram = bincount(cast(round(grayscale), 'int32') as Tensor1D,\n tensor([]),\n 256);\n $threshold = otsu($histogram, totalPixelsInImage);\n }\n\n const invCondition = inverted ?\n lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);\n\n const result = cast(mul(invCondition,255), 'int32');\n\n return result as Tensor3D;\n}\n\nfunction otsu(histogram: Tensor1D, total: number):Tensor1D {\n\n let bestThresh = tensor1d([-1]);\n let bestInBetVar = tensor1d([0]);\n let cInBetVar = tensor1d([0]);\n let classFirst, classSecond, meanFirst,\n meanSec, weightForeground, weightBack;\n\n for (let index = 0; index < histogram.size-1; index++) {\n\n classFirst = slice(histogram, 0, index + 1);\n\n classSecond = slice(histogram,index + 1);\n\n weightForeground = div(sum(classFirst),total);\n\n weightBack = div(sum(classSecond),total);\n\n const meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));\n\n meanFirst = div(meanFirstDivA, sum(classFirst) );\n\n const meanSecFill = fill(classSecond.shape, classFirst.size);\n const meanSecAdd = add(range(0,classSecond.size),meanSecFill);\n const meanSecMul = mul(classSecond, (meanSecAdd));\n meanSec = div(sum(meanSecMul), sum(classSecond));\n\n const cInBetVarSubA = sub(meanFirst, meanSec);\n const cInBetVarSubB = sub(meanFirst, meanSec);\n const cInBetVarMul = mul(weightForeground, weightBack);\n cInBetVar = mul(mul(cInBetVarMul,cInBetVarSubA), cInBetVarSubB);\n\n const condition = greater(cInBetVar, bestInBetVar);\n\n bestInBetVar = where(condition, cInBetVar, bestInBetVar);\n\n bestThresh = where(condition, tensor1d([index]), bestThresh);\n\n }\n return bestThresh;\n}\n\nexport const threshold = /* @__PURE__ */ op({ threshold_ });\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {Transform, TransformAttrs, TransformInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Applies the given transform(s) to the image(s).\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param transforms Projective transform matrix/matrices. A tensor1d of length\n * 8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0,\n * b1, b2, c0, c1], then it maps the output point (x, y) to a transformed\n * input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),\n * where k = c0 x + c1 y + 1. The transforms are inverted compared to the\n * transform mapping input points to output points.\n * @param interpolation Interpolation mode.\n * Supported values: 'nearest', 'bilinear'. Default to 'nearest'.\n * @param fillMode Points outside the boundaries of the input are filled\n * according to the given mode, one of 'constant', 'reflect', 'wrap',\n * 'nearest'. Default to 'constant'.\n * 'reflect': (d c b a | a b c d | d c b a ) The input is extended by\n * reflecting about the edge of the last pixel.\n * 'constant': (k k k k | a b c d | k k k k) The input is extended by\n * filling all values beyond the edge with the same constant value k.\n * 'wrap': (a b c d | a b c d | a b c d) The input is extended by\n * wrapping around to the opposite edge.\n * 'nearest': (a a a a | a b c d | d d d d) The input is extended by\n * the nearest pixel.\n * @param fillValue A float represents the value to be filled outside the\n * boundaries when fillMode is 'constant'.\n * @param Output dimension after the transform, [height, width]. If undefined,\n * output is the same size as input image.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction transform_(\n image: Tensor4D|TensorLike, transforms: Tensor2D|TensorLike,\n interpolation: 'nearest'|'bilinear' = 'nearest',\n fillMode: 'constant'|'reflect'|'wrap'|'nearest' = 'constant', fillValue = 0,\n outputShape?: [number, number]): Tensor4D {\n const $image = convertToTensor(image, 'image', 'transform', 'float32');\n const $transforms =\n convertToTensor(transforms, 'transforms', 'transform', 'float32');\n\n util.assert(\n $image.rank === 4,\n () => 'Error in transform: image must be rank 4,' +\n `but got rank ${$image.rank}.`);\n\n util.assert(\n $transforms.rank === 2 &&\n ($transforms.shape[0] === $image.shape[0] ||\n $transforms.shape[0] === 1) &&\n $transforms.shape[1] === 8,\n () => `Error in transform: Input transform should be batch x 8 or 1 x 8`);\n\n util.assert(\n outputShape == null || outputShape.length === 2,\n () =>\n 'Error in transform: outputShape must be [height, width] or null, ' +\n `but got ${outputShape}.`);\n\n const inputs: TransformInputs = {image: $image, transforms: $transforms};\n const attrs:\n TransformAttrs = {interpolation, fillMode, fillValue, outputShape};\n\n return ENGINE.runKernel(\n Transform, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const transform = /* @__PURE__ */ op({transform_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assert} from '../../util';\n\nimport {greaterEqual} from '../greater_equal';\nimport {less} from '../less';\nimport {lessEqual} from '../less_equal';\nimport {logicalAnd} from '../logical_and';\nimport {minimum} from '../minimum';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {range} from '../range';\nimport {reshape} from '../reshape';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\nimport {zeros} from '../zeros';\n\n/**\n * Copy a tensor setting everything outside a central band in each innermost\n * matrix to zero.\n *\n * The band part is computed as follows: Assume input has `k` dimensions\n * `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where\n * `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.\n * The indicator function\n * `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)`\n * `&& (num_upper < 0 || (n-m) <= num_upper)`\n *\n * ```js\n * const x = tf.tensor2d([[ 0, 1, 2, 3],\n * [-1, 0, 1, 2],\n * [-2, -1, 0, 1],\n * [-3, -2, -1, 0]]);\n * let y = tf.linalg.bandPart(x, 1, -1);\n * y.print(); // [[ 0, 1, 2, 3],\n * // [-1, 0, 1, 2],\n * // [ 0, -1, 0, 1],\n * // [ 0, 0 , -1, 0]]\n * let z = tf.linalg.bandPart(x, 2, 1);\n * z.print(); // [[ 0, 1, 0, 0],\n * // [-1, 0, 1, 0],\n * // [-2, -1, 0, 1],\n * // [ 0, -2, -1, 0]]\n * ```\n *\n * @param x Rank `k` tensor\n * @param numLower Number of subdiagonals to keep.\n * If negative, keep entire lower triangle.\n * @param numUpper Number of subdiagonals to keep.\n * If negative, keep entire upper triangle.\n * @returns Rank `k` tensor of the same shape as input.\n * The extracted banded tensor.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction bandPart_(\n a: T|TensorLike, numLower: number|Scalar, numUpper: number|Scalar): T {\n const $a = convertToTensor(a, 'a', 'bandPart');\n assert(\n $a.rank >= 2,\n () => `bandPart(): Rank must be at least 2, got ${$a.rank}.`);\n\n const shape = $a.shape;\n const [M, N] = $a.shape.slice(-2);\n\n let $numLower: Scalar;\n let $numUpper: Scalar;\n if (typeof numLower === 'number') {\n assert(\n numLower % 1 === 0,\n () => `bandPart(): numLower must be an integer, got ${numLower}.`);\n assert(\n numLower <= M,\n () => `bandPart(): numLower (${numLower})` +\n ` must not be greater than the number of rows (${M}).`);\n $numLower =\n convertToTensor(numLower < 0 ? M : numLower, 'numLower', 'bandPart') as\n Scalar;\n } else {\n assert(\n numLower.dtype === 'int32',\n () => `bandPart(): numLower's dtype must be an int32.`);\n // If numLower is a Scalar, checking `numLower <= M` could hurt performance,\n // but minimum(numLower, M) could avoid unexpected results.\n $numLower = where(less(numLower, 0), M, minimum(numLower, M)) as Scalar;\n }\n\n if (typeof numUpper === 'number') {\n assert(\n numUpper % 1 === 0,\n () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);\n assert(\n numUpper <= N,\n () => `bandPart(): numUpper (${numUpper})` +\n ` must not be greater than the number of columns (${N}).`);\n $numUpper =\n convertToTensor(numUpper < 0 ? N : numUpper, 'numUpper', 'bandPart') as\n Scalar;\n } else {\n assert(\n numUpper.dtype === 'int32',\n () => `bandPart(): numUpper's dtype must be an int32.`);\n $numUpper = where(less(numUpper, 0), N, minimum(numUpper, N)) as Scalar;\n }\n\n const i = reshape(range(0, M, 1, 'int32'), [-1, 1]);\n const j = range(0, N, 1, 'int32');\n const ij = sub(i, j);\n\n const inBand =\n logicalAnd(lessEqual(ij, $numLower), greaterEqual(ij, neg($numUpper)));\n\n const zero = zeros([M, N], $a.dtype);\n\n return reshape(\n stack(unstack(reshape($a, [-1, M, N]))\n .map(mat => where(inBand, mat, zero))),\n shape) as T;\n}\n\nexport const bandPart = /* @__PURE__ */ op({bandPart_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {div} from '../div';\nimport {mul} from '../mul';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {split} from '../split';\nimport {squeeze} from '../squeeze';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\n/**\n * Gram-Schmidt orthogonalization.\n *\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * let y = tf.linalg.gramSchmidt(x);\n * y.print();\n * console.log('Orthogonalized:');\n * y.dot(y.transpose()).print(); // should be nearly the identity matrix.\n * console.log('First row direction maintained:');\n * const data = await y.array();\n * console.log(data[0][1] / data[0][0]); // should be nearly 2.\n * ```\n *\n * @param xs The vectors to be orthogonalized, in one of the two following\n * formats:\n * - An Array of `tf.Tensor1D`.\n * - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows\n * of `xs`.\n * In each case, all the vectors must have the same length and the length\n * must be greater than or equal to the number of vectors.\n * @returns The orthogonalized and normalized vectors or matrix.\n * Orthogonalization means that the vectors or the rows of the matrix\n * are orthogonal (zero inner products). Normalization means that each\n * vector or each row of the matrix has an L2 norm that equals `1`.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction gramSchmidt_(xs: Tensor1D[]|Tensor2D): Tensor1D[]|Tensor2D {\n let inputIsTensor2D: boolean;\n if (Array.isArray(xs)) {\n inputIsTensor2D = false;\n assert(\n xs != null && xs.length > 0,\n () => 'Gram-Schmidt process: input must not be null, undefined, or ' +\n 'empty');\n const dim = xs[0].shape[0];\n for (let i = 1; i < xs.length; ++i) {\n assert(\n xs[i].shape[0] === dim,\n () =>\n 'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +\n `(${(xs as Tensor1D[])[i].shape[0]} vs. ${dim})`);\n }\n } else {\n inputIsTensor2D = true;\n xs = split(xs, xs.shape[0], 0).map(x => squeeze(x, [0]));\n }\n\n assert(\n xs.length <= xs[0].shape[0],\n () => `Gram-Schmidt: Number of vectors (${\n (xs as Tensor1D[]).length}) exceeds ` +\n `number of dimensions (${(xs as Tensor1D[])[0].shape[0]}).`);\n\n const ys: Tensor1D[] = [];\n const xs1d = xs;\n for (let i = 0; i < xs.length; ++i) {\n ys.push(ENGINE.tidy(() => {\n let x = xs1d[i];\n if (i > 0) {\n for (let j = 0; j < i; ++j) {\n const proj = mul(sum(mul(ys[j], x)), ys[j]);\n x = sub(x, proj);\n }\n }\n return div(x, norm(x, 'euclidean'));\n }));\n }\n\n if (inputIsTensor2D) {\n return stack(ys, 0) as Tensor2D;\n } else {\n return ys;\n }\n}\n\nexport const gramSchmidt = /* @__PURE__ */ op({gramSchmidt_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {dispose} from '../../globals';\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {clone} from '../clone';\nimport {concat} from '../concat';\nimport {div} from '../div';\nimport {eye} from '../eye';\nimport {greater} from '../greater';\nimport {matMul} from '../mat_mul';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {tensor2d} from '../tensor2d';\nimport {transpose} from '../transpose';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\n\n/**\n * Compute QR decomposition of m-by-n matrix using Householder transformation.\n *\n * Implementation based on\n * [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]\n * (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [3, 4]]);\n * let [q, r] = tf.linalg.qr(a);\n * console.log('Q');\n * q.print();\n * console.log('R');\n * r.print();\n * console.log('Orthogonalized');\n * q.dot(q.transpose()).print() // should be nearly the identity matrix.\n * console.log('Reconstructed');\n * q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];\n * ```\n *\n * @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose\n * it has the shape `[..., M, N]`.\n * @param fullMatrices An optional boolean parameter. Defaults to `false`.\n * If `true`, compute full-sized `Q`. If `false` (the default),\n * compute only the leading N columns of `Q` and `R`.\n * @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,\n * i.e., its columns all have unit norm and are mutually orthogonal.\n * If `M >= N`,\n * If `fullMatrices` is `false` (default),\n * - `Q` has a shape of `[..., M, N]`,\n * - `R` has a shape of `[..., N, N]`.\n * If `fullMatrices` is `true` (default),\n * - `Q` has a shape of `[..., M, M]`,\n * - `R` has a shape of `[..., M, N]`.\n * If `M < N`,\n * - `Q` has a shape of `[..., M, M]`,\n * - `R` has a shape of `[..., M, N]`.\n * @throws If the rank of `x` is less than 2.\n *\n * @doc {heading:'Operations',\n * subheading:'Linear Algebra',\n * namespace:'linalg'}\n */\nfunction qr_(x: Tensor, fullMatrices = false): [Tensor, Tensor] {\n assert(\n x.rank >= 2,\n () => `qr() requires input tensor to have a rank >= 2, but got rank ${\n x.rank}`);\n\n if (x.rank === 2) {\n return qr2d(x as Tensor2D, fullMatrices);\n } else {\n // Rank > 2.\n // TODO(cais): Below we split the input into individual 2D tensors,\n // perform QR decomposition on them and then stack the results back\n // together. We should explore whether this can be parallelized.\n const outerDimsProd = x.shape.slice(0, x.shape.length - 2)\n .reduce((value, prev) => value * prev);\n const x2ds = unstack(\n reshape(\n x,\n [\n outerDimsProd, x.shape[x.shape.length - 2],\n x.shape[x.shape.length - 1]\n ]),\n 0);\n const q2ds: Tensor2D[] = [];\n const r2ds: Tensor2D[] = [];\n x2ds.forEach(x2d => {\n const [q2d, r2d] = qr2d(x2d as Tensor2D, fullMatrices);\n q2ds.push(q2d);\n r2ds.push(r2d);\n });\n const q = reshape(stack(q2ds, 0), x.shape);\n const r = reshape(stack(r2ds, 0), x.shape);\n return [q, r];\n }\n}\n\nfunction qr2d(x: Tensor2D, fullMatrices = false): [Tensor2D, Tensor2D] {\n return ENGINE.tidy(() => {\n assert(\n x.shape.length === 2,\n () => `qr2d() requires a 2D Tensor, but got a ${\n x.shape.length}D Tensor.`);\n\n const m = x.shape[0];\n const n = x.shape[1];\n\n let q = eye(m); // Orthogonal transform so far.\n let r = clone(x); // Transformed matrix so far.\n\n const one2D = tensor2d([[1]], [1, 1]);\n let w: Tensor2D = clone(one2D);\n\n const iters = m >= n ? n : m;\n for (let j = 0; j < iters; ++j) {\n // This tidy within the for-loop ensures we clean up temporary\n // tensors as soon as they are no longer needed.\n const rTemp = r;\n const wTemp = w;\n const qTemp = q;\n [w, r, q] = ENGINE.tidy((): [Tensor2D, Tensor2D, Tensor2D] => {\n // Find H = I - tau * w * w', to put zeros below R(j, j).\n const rjEnd1 = slice(r, [j, j], [m - j, 1]);\n const normX = norm(rjEnd1);\n const rjj = slice(r, [j, j], [1, 1]);\n\n // The sign() function returns 0 on 0, which causes division by zero.\n const s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));\n\n const u1 = sub(rjj, mul(s, normX));\n const wPre = div(rjEnd1, u1);\n if (wPre.shape[0] === 1) {\n w = clone(one2D);\n } else {\n w = concat(\n [\n one2D,\n slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]]) as\n Tensor2D\n ],\n 0);\n }\n const tau = neg(div(matMul(s, u1), normX)) as Tensor2D;\n\n // -- R := HR, Q := QH.\n const rjEndAll = slice(r, [j, 0], [m - j, n]);\n const tauTimesW: Tensor2D = mul(tau, w);\n const wT: Tensor2D = transpose(w);\n if (j === 0) {\n r = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n } else {\n const rTimesTau: Tensor2D =\n sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n r = concat([slice(r, [0, 0], [j, n]), rTimesTau], 0);\n }\n const tawTimesWT: Tensor2D = transpose(tauTimesW);\n const qAllJEnd = slice(q, [0, j], [m, q.shape[1] - j]);\n if (j === 0) {\n q = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n } else {\n const qTimesTau: Tensor2D =\n sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n q = concat([slice(q, [0, 0], [m, j]), qTimesTau], 1);\n }\n return [w, r, q];\n });\n dispose([rTemp, wTemp, qTemp]);\n }\n\n if (!fullMatrices && m > n) {\n q = slice(q, [0, 0], [m, n]);\n r = slice(r, [0, 0], [n, n]);\n }\n\n return [q, r];\n }) as [Tensor2D, Tensor2D];\n}\n\nexport const qr = /* @__PURE__ */ op({qr_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport enum Reduction {\n NONE,\n MEAN,\n SUM,\n SUM_BY_NONZERO_WEIGHTS\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {Reduction} from '../loss_ops_utils';\nimport {mean} from '../mean';\nimport {mul} from '../mul';\nimport {notEqual} from '../not_equal';\nimport {ones} from '../ones';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sum} from '../sum';\n\n/**\n * Computes the weighted loss between two tensors.\n *\n * @param losses Tensor of shape `[batch_size, d1, ..., dN]`.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `losses`, and must be broadcastable to `losses` (i.e., all\n * dimensions must be either `1`, or the same as the corresponding\n * `losses` dimension).\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction computeWeightedLoss_(\n losses: T|TensorLike, weights?: Tensor|TensorLike,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n const $losses = convertToTensor(losses, 'losses', 'computeWeightedLoss');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'computeWeightedLoss');\n }\n\n const weightedLoss = ($weights == null) ? $losses : mul($losses, $weights);\n\n if (reduction === Reduction.NONE) {\n return weightedLoss as O;\n }\n if (reduction === Reduction.SUM) {\n return sum(weightedLoss);\n }\n if (reduction === Reduction.MEAN) {\n if ($weights == null) {\n return mean(weightedLoss);\n } else {\n const broadcastFactor = $losses.size / $weights.size;\n const result = div(sum(weightedLoss), sum($weights));\n return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) :\n result as O;\n }\n }\n if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {\n if ($weights == null) {\n return div(sum(weightedLoss), scalar($losses.size));\n } else {\n const broadcastedWeights = mul($weights, ones($losses.shape));\n\n const numNonZeros =\n cast(sum(notEqual(broadcastedWeights, scalar(0))), 'float32');\n return div(sum(weightedLoss), numNonZeros);\n }\n }\n\n throw Error(`Unknown reduction: ${reduction}`);\n}\nexport const computeWeightedLoss = /* @__PURE__ */ op({computeWeightedLoss_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {Reduction} from '../loss_ops_utils';\nimport {op} from '../operation';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the absolute difference loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n * 'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n * must be either `1`, or the same as the corresponding `losses`\n * dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n * `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction absoluteDifference_(\n labels: T|TensorLike, predictions: T|TensorLike,\n weights?: Tensor|TensorLike,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n const $labels = convertToTensor(labels, 'labels', 'absoluteDifference');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'absoluteDifference');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'absoluteDifference');\n }\n assertShapesMatch(\n $labels.shape, $predictions.shape, 'Error in absoluteDifference: ');\n\n const losses = abs(sub($labels, $predictions));\n return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const absoluteDifference = /* @__PURE__ */ op({absoluteDifference_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the cosine distance loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n * 'predictions'.\n * @param predictions The predicted outputs.\n * @param axis The dimension along which the cosine distance is computed.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n * must be either `1`, or the same as the corresponding `losses`\n * dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n * `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction cosineDistance_(\n labels: T|TensorLike, predictions: T|TensorLike, axis: number,\n weights?: Tensor|TensorLike,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n const $labels = convertToTensor(labels, 'labels', 'cosineDistance');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'cosineDistance');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'cosineDistance');\n }\n assertShapesMatch(\n $labels.shape, $predictions.shape, 'Error in cosineDistance: ');\n\n const one = scalar(1);\n const losses = sub(one, sum(mul($labels, $predictions), axis, true));\n return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const cosineDistance = /* @__PURE__ */ op({cosineDistance_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {relu} from '../relu';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the Hinge loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n * 'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n * must be either `1`, or the same as the corresponding `losses`\n * dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n * `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction hingeLoss_(\n labels: T|TensorLike, predictions: T|TensorLike,\n weights?: Tensor|TensorLike,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n let $labels = convertToTensor(labels, 'labels', 'hingeLoss');\n const $predictions = convertToTensor(predictions, 'predictions', 'hingeLoss');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'hingeLoss');\n }\n assertShapesMatch($labels.shape, $predictions.shape, 'Error in hingeLoss: ');\n\n const one = scalar(1);\n // Convert binary labels to (-1, 1)\n $labels = sub(mul(scalar(2), $labels), one);\n const losses = relu(sub(one, mul($labels, $predictions)));\n return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const hingeLoss = /* @__PURE__ */ op({hingeLoss_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {add} from '../add';\nimport {Reduction} from '../loss_ops_utils';\nimport {minimum} from '../minimum';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {square} from '../square';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the Huber loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n * 'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n * must be either `1`, or the same as the corresponding `losses`\n * dimension).\n * @param delta Point where Huber loss changes from quadratic to linear.\n * @param reduction Type of reduction to apply to loss. Should be of type\n * `Reduction`.\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction huberLoss_(\n labels: T|TensorLike, predictions: T|TensorLike,\n weights?: Tensor|TensorLike, delta = 1.0,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n const $labels = convertToTensor(labels, 'labels', 'huberLoss');\n const $predictions = convertToTensor(predictions, 'predictions', 'huberLoss');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'huberLoss');\n }\n assertShapesMatch($labels.shape, $predictions.shape, 'Error in huberLoss: ');\n\n const deltaScalar = scalar(delta);\n const error = abs(sub($predictions, $labels));\n const quadratic = minimum(error, deltaScalar);\n const linear = sub(error, quadratic);\n\n const losses =\n add(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));\n return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const huberLoss = /* @__PURE__ */ op({huberLoss_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {add} from '../add';\nimport {log} from '../log';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the log loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n * 'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n * must be either `1`, or the same as the corresponding `losses`\n * dimension).\n * @param epsilon A small increment to avoid taking log of zero\n * @param reduction Type of reduction to apply to loss. Should be of type\n * `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction logLoss_(\n labels: T|TensorLike, predictions: T|TensorLike,\n weights?: Tensor|TensorLike, epsilon = 1e-7,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n const $labels = convertToTensor(labels, 'labels', 'logLoss');\n const $predictions = convertToTensor(predictions, 'predictions', 'logLoss');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'logLoss');\n }\n assertShapesMatch($labels.shape, $predictions.shape, 'Error in logLoss: ');\n\n const one = scalar(1);\n const epsilonScalar = scalar(epsilon);\n\n const l1 = neg(mul($labels, log(add($predictions, epsilonScalar))));\n const l2 =\n mul(sub(one, $labels), log(add(sub(one, $predictions), epsilonScalar)));\n const losses = sub(l1, l2);\n return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const logLoss = /* @__PURE__ */ op({logLoss_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {op} from '../operation';\nimport {squaredDifference} from '../squared_difference';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the mean squared error between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n * 'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n * `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n * must be either `1`, or the same as the corresponding `losses`\n * dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n * `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction meanSquaredError_(\n labels: T|TensorLike, predictions: T|TensorLike,\n weights?: Tensor|TensorLike,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n const $labels = convertToTensor(labels, 'labels', 'meanSquaredError');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'meanSquaredError');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'meanSquaredError');\n }\n assertShapesMatch(\n $labels.shape, $predictions.shape, 'Error in meanSquaredError: ');\n\n const losses = squaredDifference($labels, $predictions);\n return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const meanSquaredError = /* @__PURE__ */ op({meanSquaredError_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {add} from '../add';\nimport {exp} from '../exp';\nimport {log1p} from '../log1p';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {relu} from '../relu';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\nfunction sigmoidCrossEntropyWithLogits_(\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_(\n multiClassLabels: T|TensorLike, logits: T|TensorLike,\n weights?: Tensor|TensorLike, labelSmoothing = 0,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n let $multiClassLabels = convertToTensor(\n multiClassLabels, 'multiClassLabels', 'sigmoidCrossEntropy');\n const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropy');\n let $weights: Tensor = null;\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'sigmoidCrossEntropy');\n }\n assertShapesMatch(\n $multiClassLabels.shape, $logits.shape, 'Error in sigmoidCrossEntropy: ');\n\n if (labelSmoothing > 0) {\n const labelSmoothingScalar = scalar(labelSmoothing);\n const one = scalar(1);\n const half = scalar(0.5);\n\n $multiClassLabels =\n add(mul($multiClassLabels, sub(one, labelSmoothingScalar)),\n mul(half, labelSmoothingScalar));\n }\n const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);\n\n return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const sigmoidCrossEntropy = /* @__PURE__ */ op({sigmoidCrossEntropy_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {customGrad} from '../../gradients';\nimport {Tensor} from '../../tensor';\nimport {GradSaveFunc} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {add} from '../add';\nimport {expandShapeToKeepDim} from '../axis_util';\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {exp} from '../exp';\nimport {logSumExp} from '../log_sum_exp';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes softmax cross entropy between logits and labels.\n *\n * Measures the probability error in discrete classification tasks in which\n * the classes are mutually exclusive (each entry is in exactly one class).\n * For example, each CIFAR-10 image is labeled with one and only one label: an\n * image can be a dog or a truck, but not both.\n *\n * `NOTE`: While the classes are mutually exclusive, their probabilities need\n * not be. All that is required is that each row of labels is a valid\n * probability distribution. If they are not, the computation of the gradient\n * will be incorrect.\n *\n * `WARNING`: This op expects unscaled logits, since it performs a softmax on\n * logits internally for efficiency. Do not call this op with the output of\n * softmax, as it will produce incorrect results.\n *\n * logits and labels must have the same shape, e.g. [batch_size, num_classes]\n * and the same dtype.\n * @param labels The labels array.\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n * which indicates the last dimension.\n */\nfunction softmaxCrossEntropyWithLogits_(\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_(\n onehotLabels: T|TensorLike, logits: T|TensorLike,\n weights?: Tensor|TensorLike, labelSmoothing = 0,\n reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n let $onehotLabels =\n convertToTensor(onehotLabels, 'onehotLabels', 'softmaxCrossEntropy');\n const $logits = convertToTensor(logits, 'logits', 'softmaxCrossEntropy');\n let $weights: Tensor = null;\n\n if (weights != null) {\n $weights = convertToTensor(weights, 'weights', 'softmaxCrossEntropy');\n }\n\n assertShapesMatch(\n $onehotLabels.shape, $logits.shape, 'Error in softmaxCrossEntropy: ');\n\n if (labelSmoothing > 0) {\n const labelSmoothingScalar = scalar(labelSmoothing);\n const one = scalar(1);\n const numClasses = scalar($onehotLabels.shape[1]);\n\n $onehotLabels =\n add(mul($onehotLabels, sub(one, labelSmoothingScalar)),\n div(labelSmoothingScalar, numClasses));\n }\n\n const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);\n\n return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const softmaxCrossEntropy = /* @__PURE__ */ op({softmaxCrossEntropy_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseFillEmptyRows, SparseFillEmptyRowsInputs} from '../../kernel_names';\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {ScalarLike, TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * The input SparseTensor is represented via the map of inputs {`indices`,\n * `values`, `denseShape`}. The output SparseTensor has the same `denseShape`\n * but with indices `outputIndices` and values `outputValues`. This op inserts a\n * single entry for every row that doesn't have any values. The index is created\n * as `[row, 0, ..., 0]` and the inserted value is `defaultValue`.\n *\n * For example, suppose `spInput` has shape [5, 6] and non-empty values:\n * [0, 1]: a\n * [0, 3]: b\n * [2, 0]: c\n * [3, 1]: d\n *\n * Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:\n * [0, 1]: a\n * [0, 3]: b\n * [1, 0]: `defaultValue`\n * [2, 0]: c\n * [3, 1]: d\n * [4, 0]: `defaultValue`\n *\n * The output SparseTensor will be in row-major order and will have the same\n * shape as the input.\n *\n * This op also returns an indicator vector shaped [dense_shape[0]] such that\n * emptyRowIndicator[i] = True iff row i was an empty row.\n *\n * And a reverse index map vector shaped [indices.shape[0]] that is used during\n * backpropagation, reverseIndexMap[i] = outi s.t. indices[i, j] ==\n * outputIndices[outi, j] for all j\n *\n * ```js\n * const result = tf.sparse.sparseFillEmptyRows(\n * [[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]],\n * [0, 10, 13, 14, 32, 33], [5, 6], -1);\n * console.log(result);\n * result['outputIndices'].print(); // [[0, 0], [1, 0], [1, 3], [1, 4],\n * // [2, 0], [3, 2], [3, 3], [4, 0]]\n * result['outputValues'].print(); // [0, 10, 13, 14,-1, 32, 33, -1]\n * result['emptyRowIndicator'].print(); // [false, false, true, false, true]\n * result['reverseIndexMap'].print(); // [0, 1, 2, 3, 5, 6]\n * ```\n * @param indices: 2-D. The indices of the sparse tensor.\n * @param values: 1-D. The values of the sparse tensor.\n * @param denseShape: 1-D. The shape of the sparse tensor.\n * @param defaultValue: 0-D. Default value to insert into location [row, 0, ...,\n * 0] for rows missing from the input sparse tensor.\n * @return A map with the following properties:\n * - outputIndices\n * - outputValues: 1-D. The values of the filled sparse tensor.\n * - emptyRowIndicator: 1-D. Whether the dense row was missing in the input\n * sparse tensor.\n * - reverseIndexMap: 1-D. A map from the input indices to the output\n * indices.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseFillEmptyRows_(\n indices: Tensor2D|TensorLike, values: Tensor1D|TensorLike,\n denseShape: Tensor1D|TensorLike,\n defaultValue: Scalar|ScalarLike): NamedTensorMap {\n const $indices =\n convertToTensor(indices, 'indices', 'sparseFillEmptyRows', 'int32');\n const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');\n const $denseShape =\n convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows', 'int32');\n const $defaultValue = convertToTensor(\n defaultValue, 'defaultValue', 'sparseFillEmptyRows', $values.dtype);\n\n if ($indices.rank !== 2) {\n throw new Error(`Indices should be Tensor2D but received shape\n ${$indices.shape}`);\n }\n if ($values.rank !== 1) {\n throw new Error(\n `Values should be Tensor1D but received shape ${$values.shape}`);\n }\n if ($denseShape.rank !== 1) {\n throw new Error(`Dense shape should be Tensor1D but received shape ${\n $denseShape.shape}`);\n }\n if ($defaultValue.rank !== 0) {\n throw new Error(`Default value should be a scalar but received shape ${\n $defaultValue.shape}`);\n }\n\n const inputs: SparseFillEmptyRowsInputs = {\n indices: $indices,\n values: $values,\n denseShape: $denseShape,\n defaultValue: $defaultValue\n };\n\n const result: Tensor[] = ENGINE.runKernel(SparseFillEmptyRows, inputs as {});\n return {\n outputIndices: result[0],\n outputValues: result[1],\n emptyRowIndicator: result[2],\n reverseIndexMap: result[3]\n };\n}\n\nexport const sparseFillEmptyRows = /* @__PURE__ */ op({sparseFillEmptyRows_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseReshape, SparseReshapeInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * This operation has the same semantics as reshape on the represented dense\n * tensor. The `inputIndices` are recomputed based on the requested `newShape`.\n * If one component of `newShape` is the special value -1, the size of that\n * dimension is computed so that the total dense size remains constant. At most\n * one component of `newShape` can be -1. The number of dense elements implied\n * by `newShape` must be the same as the number of dense elements originally\n * implied by `inputShape`. Reshaping does not affect the order of values in the\n * SparseTensor. If the input tensor has rank R_in and N non-empty values, and\n * `newShape` has length R_out, then `inputIndices` has shape [N, R_in],\n * `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and\n * `outputShape` has length R_out.\n *\n * ```js\n * const result = tf.sparse.sparseReshape(\n * [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],\n * [2, 3, 6], [9, -1]);\n * console.log(result);\n * result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]\n * result['outputShape'].print(); // [9, 4]\n * ```\n * @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty\n * values in a SparseTensor.\n * @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense\n * shape.\n * @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.\n * @return A map with the following properties:\n * - outputIndices: 2-D. N x R_out matrix with the updated indices of\n * non-empty values in the output SparseTensor.\n * - outputShape: 1-D. R_out vector with the full dense shape of the output\n * SparseTensor. This is the same as newShape but with any -1 dimensions\n * filled in.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseReshape_(\n inputIndices: Tensor2D|TensorLike, inputShape: Tensor1D|TensorLike,\n newShape: Tensor1D|TensorLike): NamedTensorMap {\n const $inputIndices =\n convertToTensor(inputIndices, 'inputIndices', 'sparseReshape', 'int32');\n const $inputShape =\n convertToTensor(inputShape, 'inputShape', 'sparseReshape', 'int32');\n const $newShape =\n convertToTensor(newShape, 'newShape', 'sparseReshape', 'int32');\n\n if ($inputIndices.rank !== 2) {\n throw new Error(`Input indices should be Tensor2D but received shape\n ${$inputIndices.shape}`);\n }\n if ($inputShape.rank !== 1) {\n throw new Error(`Input shape should be Tensor1D but received shape ${\n $inputShape.shape}`);\n }\n if ($newShape.rank !== 1) {\n throw new Error(\n `New shape should be Tensor1D but received shape ${$newShape.shape}`);\n }\n\n const inputs: SparseReshapeInputs = {\n inputIndices: $inputIndices,\n inputShape: $inputShape,\n newShape: $newShape\n };\n const result: Tensor[] = ENGINE.runKernel(SparseReshape, inputs as {});\n return {outputIndices: result[0], outputShape: result[1]};\n}\n\nexport const sparseReshape = /* @__PURE__ */ op({sparseReshape_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentMean, SparseSegmentMeanInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the mean along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [6,7,8,9]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentMean(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentMean(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentMean(c,\n * tf.tensor1d([0, 1, 2], 'int32'),\n * tf.tensor1d([0, 1, 1], 'int32'));\n * result3.print(); // [[1.0, 2.0, 3.0, 4.0], [2.5, 2.5, 2.5, 2.5]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n * assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n * segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n * should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n * the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentMean_(\n data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n segmentIds: Tensor1D|TensorLike): Tensor {\n const $data = convertToTensor(data, 'data', 'sparseSegmentMean');\n const $indices =\n convertToTensor(indices, 'indices', 'sparseSegmentMean', 'int32');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentMean', 'int32');\n\n if ($data.rank < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if ($indices.rank !== 1) {\n throw new Error(`Indices should be Tensor1D but received shape\n ${$indices.shape}`);\n }\n if ($segmentIds.rank !== 1) {\n throw new Error(`Segment ids should be Tensor1D but received shape\n ${$segmentIds.shape}`);\n }\n\n const inputs: SparseSegmentMeanInputs = {\n data: $data,\n indices: $indices,\n segmentIds: $segmentIds\n };\n\n return ENGINE.runKernel(SparseSegmentMean, inputs as {});\n}\n\nexport const sparseSegmentMean = /* @__PURE__ */ op({sparseSegmentMean_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentSum, SparseSegmentSumInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the sum along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentSum(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentSum(c,\n * tf.tensor1d([0, 1], 'int32'),\n * tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentSum(c,\n * tf.tensor1d([0, 1, 2], 'int32'),\n * tf.tensor1d([0, 0, 1], 'int32'));\n * result3.print(); // [[0, 0, 0, 0], [5, 6, 7, 8]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n * assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n * segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n * should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n * the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentSum_(\n data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n segmentIds: Tensor1D|TensorLike): Tensor {\n const $data = convertToTensor(data, 'data', 'sparseSegmentSum');\n const $indices =\n convertToTensor(indices, 'indices', 'sparseSegmentSum', 'int32');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentSum', 'int32');\n\n if ($data.rank < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if ($indices.rank !== 1) {\n throw new Error(`Indices should be Tensor1D but received shape\n ${$indices.shape}`);\n }\n if ($segmentIds.rank !== 1) {\n throw new Error(`Segment ids should be Tensor1D but received shape\n ${$segmentIds.shape}`);\n }\n\n const inputs: SparseSegmentSumInputs = {\n data: $data,\n indices: $indices,\n segmentIds: $segmentIds\n };\n\n return ENGINE.runKernel(SparseSegmentSum, inputs as {});\n}\n\nexport const sparseSegmentSum = /* @__PURE__ */ op({sparseSegmentSum_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringNGrams, StringNGramsAttrs, StringNGramsInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Creates ngrams from ragged string data.\n *\n * This op accepts a ragged tensor with 1 ragged dimension containing only\n * strings and outputs a ragged tensor with 1 ragged dimension containing ngrams\n * of that string, joined along the innermost axis.\n *\n * ```js\n * const result = tf.string.stringNGrams(\n * ['a', 'b', 'c', 'd'], tf.tensor1d([0, 2, 4], 'int32'),\n * '|', [1, 2], 'LP', 'RP', -1, false);\n * result['nGrams'].print(); // ['a', 'b', 'LP|a', 'a|b', 'b|RP',\n * // 'c', 'd', 'LP|c', 'c|d', 'd|RP']\n * result['nGramsSplits'].print(); // [0, 5, 10]\n * ```\n * @param data: The values tensor of the ragged string tensor to make ngrams out\n * of. Must be a 1D string tensor.\n * @param dataSplits: The splits tensor of the ragged string tensor to make\n * ngrams out of.\n * @param separator: The string to append between elements of the token. Use \"\"\n * for no separator.\n * @param nGramWidths: The sizes of the ngrams to create.\n * @param leftPad: The string to use to pad the left side of the ngram sequence.\n * Only used if pad_width !== 0.\n * @param rightPad: The string to use to pad the right side of the ngram\n * sequence. Only used if pad_width !== 0.\n * @param padWidth: The number of padding elements to add to each side of each\n * sequence. Note that padding will never be greater than `nGramWidths`-1\n * regardless of this value. If `padWidth`=-1, then add max(`nGramWidths`)-1\n * elements.\n * @param preserveShortSequences: If true, then ensure that at least one ngram\n * is generated for each input sequence. In particular, if an input sequence\n * is shorter than min(ngramWidth) + 2*padWidth, then generate a single\n * ngram containing the entire sequence. If false, then no ngrams are\n * generated for these short input sequences.\n * @return A map with the following properties:\n * - nGrams: The values tensor of the output ngrams ragged tensor.\n * - nGramsSplits: The splits tensor of the output ngrams ragged tensor.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringNGrams_(\n data: Tensor1D|TensorLike, dataSplits: Tensor|TensorLike, separator: string,\n nGramWidths: number[], leftPad: string, rightPad: string, padWidth: number,\n preserveShortSequences: boolean): NamedTensorMap {\n const $data = convertToTensor(data, 'data', 'stringNGrams', 'string');\n if ($data.dtype !== 'string') {\n throw new Error('Data must be of datatype string');\n }\n if ($data.shape.length !== 1) {\n throw new Error(`Data must be a vector, saw: ${$data.shape}`);\n }\n\n const $dataSplits = convertToTensor(dataSplits, 'dataSplits', 'stringNGrams');\n if ($dataSplits.dtype !== 'int32') {\n throw new Error('Data splits must be of datatype int32');\n }\n\n const attrs: StringNGramsAttrs = {\n separator,\n nGramWidths,\n leftPad,\n rightPad,\n padWidth,\n preserveShortSequences\n };\n\n const inputs: StringNGramsInputs = {data: $data, dataSplits: $dataSplits};\n const result: Tensor[] =\n ENGINE.runKernel(StringNGrams, inputs as {}, attrs as {});\n return {nGrams: result[0], nGramsSplits: result[1]};\n}\n\nexport const stringNGrams = /* @__PURE__ */ op({stringNGrams_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringSplit, StringSplitAttrs, StringSplitInputs} from '../../kernel_names';\nimport {Scalar, Tensor, Tensor1D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {ScalarLike, TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Split elements of `input` based on `delimiter` into a SparseTensor .\n *\n * Let N be the size of source (typically N will be the batch size). Split each\n * element of `input` based on `delimiter` and return a SparseTensor containing\n * the splitted tokens. Empty tokens are ignored if `skipEmpty` is set to True.\n *\n * `delimiter` can be empty, or a string of split characters. If `delimiter` is\n * an empty string, each element of `input` is split into individual\n * character strings. Otherwise every character of `delimiter` is a potential\n * split point.\n *\n * ```js\n * const result = tf.string.stringSplit(['hello world', 'a b c'], ' ');\n * result['indices'].print(); // [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]]\n * result['values'].print(); // ['hello', 'world', 'a', 'b', 'c']\n * result['shape'].print(); // [2, 3]\n * ```\n * @param input: 1-D. Strings to split.\n * @param delimiter: 0-D. Delimiter characters, or empty string.\n * @param skipEmpty: Optional. If true, skip the empty strings from the result.\n * Defaults to true.\n * @return A map with the following properties:\n * - indices: A dense matrix of int32 representing the indices of the sparse\n * tensor.\n * - values: A vector of strings corresponding to the splited values.\n * - shape: a length-2 vector of int32 representing the shape of the sparse\n * tensor, where the first value is N and the second value is the maximum number\n * of tokens in a single input entry.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringSplit_(\n input: Tensor1D|TensorLike, delimiter: Scalar|ScalarLike,\n skipEmpty = true): NamedTensorMap {\n const $input = convertToTensor(input, 'input', 'stringSplit', 'string');\n const $delimiter =\n convertToTensor(delimiter, 'delimiter', 'stringSplit', 'string');\n\n if ($input.rank !== 1) {\n throw new Error(\n `Input should be Tensor1D but received shape ${$input.shape}`);\n }\n if ($delimiter.rank !== 0) {\n throw new Error(\n `Delimiter should be a scalar but received shape ${$delimiter.shape}`);\n }\n\n const attrs: StringSplitAttrs = {skipEmpty};\n const inputs: StringSplitInputs = {input: $input, delimiter: $delimiter};\n const result: Tensor[] =\n ENGINE.runKernel(StringSplit, inputs as {}, attrs as {});\n return {indices: result[0], values: result[1], shape: result[2]};\n}\n\nexport const stringSplit = /* @__PURE__ */ op({stringSplit_});\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Converts each string in the input Tensor to its hash mod by a number of\n * buckets.\n *\n * The hash function is deterministic on the content of the string within the\n * process and will never change. However, it is not suitable for cryptography.\n * This function may be used when CPU time is scarce and inputs are trusted or\n * unimportant. There is a risk of adversaries constructing inputs that all hash\n * to the same bucket.\n *\n * ```js\n * const result = tf.string.stringToHashBucketFast(\n * ['Hello', 'TensorFlow', '2.x'], 3);\n * result.print(); // [0, 2, 2]\n * ```\n * @param input: The strings to assign a hash bucket.\n * @param numBuckets: The number of buckets.\n * @return A Tensor of the same shape as the input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringToHashBucketFast_(\n input: Tensor|TensorLike, numBuckets: number): Tensor {\n const $input =\n convertToTensor(input, 'input', 'stringToHashBucketFast', 'string');\n const attrs: StringToHashBucketFastAttrs = {numBuckets};\n\n if (numBuckets <= 0) {\n throw new Error(`Number of buckets must be at least 1`);\n }\n\n const inputs: StringToHashBucketFastInputs = {input: $input};\n return ENGINE.runKernel(StringToHashBucketFast, inputs as {}, attrs as {});\n}\n\nexport const stringToHashBucketFast = /* @__PURE__ */ op({stringToHashBucketFast_});\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StaticRegexReplace, StaticRegexReplaceAttrs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Replace the match of a `pattern` in `input` with `rewrite`.\n *\n * ```js\n * const result = tf.string.staticRegexReplace(\n * ['format this spacing better'], ' +', ' ');\n * result.print(); // ['format this spacing better']\n * ```\n * @param input: A Tensor of type string. The text to be processed.\n * @param pattern: A string. The regular expression to match the input.\n * @param rewrite: A string. The rewrite to be applied to the matched\n * expression.\n * @param replaceGlobal: An optional bool. Defaults to True. If True, the\n * replacement is global, otherwise the replacement is done only on the\n * first match.\n * @return A Tensor of type string.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction staticRegexReplace_(\n input: Tensor | TensorLike, pattern: string, rewrite: string,\n replaceGlobal=true): Tensor {\n\n const $input = convertToTensor(input, 'input', 'staticRegexReplace',\n 'string');\n const attrs: StaticRegexReplaceAttrs = {pattern, rewrite, replaceGlobal};\n return ENGINE.runKernel(StaticRegexReplace, {x: $input},\n attrs as unknown as NamedAttrMap);\n}\n\nexport const staticRegexReplace = /* @__PURE__ */ op({staticRegexReplace_});\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Modularized ops.\nexport {abs} from './abs';\nexport {acos} from './acos';\nexport {acosh} from './acosh';\nexport {add} from './add';\nexport {addN} from './add_n';\nexport {all} from './all';\nexport {any} from './any';\nexport {argMax} from './arg_max';\nexport {argMin} from './arg_min';\nexport {asin} from './asin';\nexport {asinh} from './asinh';\nexport {atan} from './atan';\nexport {atan2} from './atan2';\nexport {atanh} from './atanh';\nexport {avgPool} from './avg_pool';\nexport {avgPool3d} from './avg_pool_3d';\nexport {basicLSTMCell} from './basic_lstm_cell';\nexport {batchToSpaceND} from './batch_to_space_nd';\nexport {batchNorm} from './batchnorm';\nexport {batchNorm2d} from './batchnorm2d';\nexport {batchNorm3d} from './batchnorm3d';\nexport {batchNorm4d} from './batchnorm4d';\nexport {bincount} from './bincount';\nexport {bitwiseAnd} from './bitwise_and';\nexport {broadcastArgs} from './broadcast_args';\nexport {broadcastTo} from './broadcast_to';\nexport {buffer} from './buffer';\nexport {cast} from './cast';\nexport {ceil} from './ceil';\nexport {clipByValue} from './clip_by_value';\nexport {clone} from './clone';\nexport {complex} from './complex';\nexport {concat} from './concat';\nexport {concat1d} from './concat_1d';\nexport {concat2d} from './concat_2d';\nexport {concat3d} from './concat_3d';\nexport {concat4d} from './concat_4d';\nexport {conv1d} from './conv1d';\nexport {conv2d} from './conv2d';\nexport {conv2dTranspose} from './conv2d_transpose';\nexport {conv3d} from './conv3d';\nexport {conv3dTranspose} from './conv3d_transpose';\nexport {cos} from './cos';\nexport {cosh} from './cosh';\nexport {cumprod} from './cumprod';\nexport {cumsum} from './cumsum';\nexport {denseBincount} from './dense_bincount';\nexport {depthToSpace} from './depth_to_space';\nexport {depthwiseConv2d} from './depthwise_conv2d';\nexport {diag} from './diag';\nexport {dilation2d} from './dilation2d';\nexport {div} from './div';\nexport {divNoNan} from './div_no_nan';\nexport {dot} from './dot';\nexport {einsum} from './einsum';\nexport {elu} from './elu';\nexport {ensureShape} from './ensure_shape';\nexport {equal} from './equal';\nexport {erf} from './erf';\nexport {euclideanNorm} from './euclidean_norm';\nexport {exp} from './exp';\nexport {expandDims} from './expand_dims';\nexport {expm1} from './expm1';\nexport {eye} from './eye';\nexport {fill} from './fill';\nexport {floor} from './floor';\nexport {floorDiv} from './floorDiv';\nexport {gather} from './gather';\nexport {greater} from './greater';\nexport {greaterEqual} from './greater_equal';\nexport {imag} from './imag';\nexport {isFinite} from './is_finite';\nexport {isInf} from './is_inf';\nexport {isNaN} from './is_nan';\nexport {leakyRelu} from './leaky_relu';\nexport {less} from './less';\nexport {lessEqual} from './less_equal';\nexport {linspace} from './linspace';\nexport {localResponseNormalization} from './local_response_normalization';\nexport {log} from './log';\nexport {log1p} from './log1p';\nexport {logSigmoid} from './log_sigmoid';\nexport {logSoftmax} from './log_softmax';\nexport {logSumExp} from './log_sum_exp';\nexport {logicalAnd} from './logical_and';\nexport {logicalNot} from './logical_not';\nexport {logicalOr} from './logical_or';\nexport {logicalXor} from './logical_xor';\nexport {lowerBound} from './lower_bound';\nexport {matMul} from './mat_mul';\nexport {max} from './max';\nexport {maxPool} from './max_pool';\nexport {maxPool3d} from './max_pool_3d';\nexport {maxPoolWithArgmax} from './max_pool_with_argmax';\nexport {maximum} from './maximum';\nexport {mean} from './mean';\nexport {meshgrid} from './meshgrid';\nexport {min} from './min';\nexport {minimum} from './minimum';\nexport {mirrorPad} from './mirror_pad';\nexport {mod} from './mod';\nexport {moments} from './moments';\nexport {mul} from './mul';\nexport {LSTMCellFunc, multiRNNCell} from './multi_rnn_cell';\nexport {multinomial} from './multinomial';\nexport {neg} from './neg';\nexport {notEqual} from './not_equal';\nexport {oneHot} from './one_hot';\nexport {ones} from './ones';\nexport {onesLike} from './ones_like';\nexport {outerProduct} from './outer_product';\nexport {pad} from './pad';\nexport {pad1d} from './pad1d';\nexport {pad2d} from './pad2d';\nexport {pad3d} from './pad3d';\nexport {pad4d} from './pad4d';\nexport {pool} from './pool';\nexport {pow} from './pow';\nexport {prelu} from './prelu';\nexport {print} from './print';\nexport {prod} from './prod';\nexport {raggedGather} from './ragged_gather';\nexport {raggedRange} from './ragged_range';\nexport {raggedTensorToTensor} from './ragged_tensor_to_tensor';\nexport {rand} from './rand';\nexport {randomGamma} from './random_gamma';\nexport {randomNormal} from './random_normal';\nexport {randomStandardNormal} from './random_standard_normal';\nexport {randomUniform} from './random_uniform';\nexport {randomUniformInt} from './random_uniform_int';\nexport {range} from './range';\nexport {real} from './real';\nexport {reciprocal} from './reciprocal';\nexport {relu} from './relu';\nexport {relu6} from './relu6';\nexport {reshape} from './reshape';\nexport {reverse} from './reverse';\nexport {reverse1d} from './reverse_1d';\nexport {reverse2d} from './reverse_2d';\nexport {reverse3d} from './reverse_3d';\nexport {reverse4d} from './reverse_4d';\nexport {round} from './round';\nexport {rsqrt} from './rsqrt';\nexport {scalar} from './scalar';\nexport {selu} from './selu';\nexport {separableConv2d} from './separable_conv2d';\nexport {setdiff1dAsync} from './setdiff1d_async';\nexport {sigmoid} from './sigmoid';\nexport {sign} from './sign';\nexport {sin} from './sin';\nexport {sinh} from './sinh';\nexport {slice} from './slice';\nexport {slice1d} from './slice1d';\nexport {slice2d} from './slice2d';\nexport {slice3d} from './slice3d';\nexport {slice4d} from './slice4d';\nexport {softmax} from './softmax';\nexport {softplus} from './softplus';\nexport {spaceToBatchND} from './space_to_batch_nd';\nexport {fft} from './spectral/fft';\nexport {ifft} from './spectral/ifft';\nexport {irfft} from './spectral/irfft';\nexport {rfft} from './spectral/rfft';\nexport {split} from './split';\nexport {sqrt} from './sqrt';\nexport {square} from './square';\nexport {squaredDifference} from './squared_difference';\nexport {squeeze} from './squeeze';\nexport {stack} from './stack';\nexport {step} from './step';\nexport {stridedSlice} from './strided_slice';\nexport {sub} from './sub';\nexport {sum} from './sum';\nexport {tan} from './tan';\nexport {tanh} from './tanh';\nexport {tensor} from './tensor';\nexport {tensor1d} from './tensor1d';\nexport {tensor2d} from './tensor2d';\nexport {tensor3d} from './tensor3d';\nexport {tensor4d} from './tensor4d';\nexport {tensor5d} from './tensor5d';\nexport {tensor6d} from './tensor6d';\nexport {tensorScatterUpdate} from './tensor_scatter_update';\nexport {tile} from './tile';\nexport {topk} from './topk';\nexport {truncatedNormal} from './truncated_normal';\nexport {unique} from './unique';\nexport {unsortedSegmentSum} from './unsorted_segment_sum';\nexport {unstack} from './unstack';\nexport {upperBound} from './upper_bound';\nexport {variable} from './variable';\nexport {where} from './where';\nexport {whereAsync} from './where_async';\nexport {zeros} from './zeros';\nexport {zerosLike} from './zeros_like';\n\nexport * from './boolean_mask';\nexport * from './transpose';\nexport * from './norm';\nexport * from './moving_average';\nexport * from './scatter_nd';\nexport * from './search_sorted';\nexport * from './sparse_to_dense';\nexport * from './gather_nd';\nexport * from './dropout';\nexport * from './signal_ops_util';\nexport * from './in_top_k';\n\nexport {op, OP_SCOPE_SUFFIX} from './operation';\n\nimport {rfft} from './spectral/rfft';\nimport {fft} from './spectral/fft';\nimport {ifft} from './spectral/ifft';\nimport {irfft} from './spectral/irfft';\nconst spectral = {\n fft,\n ifft,\n rfft,\n irfft\n};\n\nimport * as fused from './fused_ops';\n\nimport {hammingWindow} from './signal/hamming_window';\nimport {hannWindow} from './signal/hann_window';\nimport {frame} from './signal/frame';\nimport {stft} from './signal/stft';\nconst signal = {\n hammingWindow,\n hannWindow,\n frame,\n stft,\n};\n\n// Image Ops namespace\nimport {cropAndResize} from './image/crop_and_resize';\nimport {flipLeftRight} from './image/flip_left_right';\nimport {grayscaleToRGB} from './image/grayscale_to_rgb';\nimport {rgbToGrayscale} from './image/rgb_to_grayscale';\nimport {rotateWithOffset} from './image/rotate_with_offset';\nimport {nonMaxSuppression} from './image/non_max_suppression';\nimport {nonMaxSuppressionAsync} from './image/non_max_suppression_async';\nimport {nonMaxSuppressionWithScore} from './image/non_max_suppression_with_score';\nimport {nonMaxSuppressionWithScoreAsync} from './image/non_max_suppression_with_score_async';\nimport {nonMaxSuppressionPadded} from './image/non_max_suppression_padded';\nimport {nonMaxSuppressionPaddedAsync} from './image/non_max_suppression_padded_async';\nimport {resizeBilinear} from './image/resize_bilinear';\nimport {resizeNearestNeighbor} from './image/resize_nearest_neighbor';\nimport {threshold} from './image/threshold';\nimport {transform} from './image/transform';\nconst image = {\n flipLeftRight,\n grayscaleToRGB,\n resizeNearestNeighbor,\n resizeBilinear,\n rgbToGrayscale,\n rotateWithOffset,\n cropAndResize,\n nonMaxSuppression,\n nonMaxSuppressionAsync,\n nonMaxSuppressionWithScore,\n nonMaxSuppressionWithScoreAsync,\n nonMaxSuppressionPadded,\n nonMaxSuppressionPaddedAsync,\n threshold,\n transform\n};\n\n// linalg namespace\nimport {bandPart} from './linalg/band_part';\nimport {gramSchmidt} from './linalg/gram_schmidt';\nimport {qr} from './linalg/qr';\nconst linalg = {\n bandPart,\n gramSchmidt,\n qr\n};\n\n// losses namespace;\nimport {absoluteDifference} from './losses/absolute_difference';\nimport {computeWeightedLoss} from './losses/compute_weighted_loss';\nimport {cosineDistance} from './losses/cosine_distance';\nimport {hingeLoss} from './losses/hinge_loss';\nimport {huberLoss} from './losses/huber_loss';\nimport {logLoss} from './losses/log_loss';\nimport {meanSquaredError} from './losses/mean_squared_error';\nimport {sigmoidCrossEntropy} from './losses/sigmoid_cross_entropy';\nimport {softmaxCrossEntropy} from './losses/softmax_cross_entropy';\nconst losses = {\n absoluteDifference,\n computeWeightedLoss,\n cosineDistance,\n hingeLoss,\n huberLoss,\n logLoss,\n meanSquaredError,\n sigmoidCrossEntropy,\n softmaxCrossEntropy\n};\n\nimport {sparseFillEmptyRows} from './sparse/sparse_fill_empty_rows';\nimport {sparseReshape} from './sparse/sparse_reshape';\nimport {sparseSegmentMean} from './sparse/sparse_segment_mean';\nimport {sparseSegmentSum} from './sparse/sparse_segment_sum';\nconst sparse = {\n sparseFillEmptyRows,\n sparseReshape,\n sparseSegmentMean,\n sparseSegmentSum\n};\n\nimport {stringNGrams} from './string/string_n_grams';\nimport {stringSplit} from './string/string_split';\nimport {stringToHashBucketFast} from './string/string_to_hash_bucket_fast';\nimport {staticRegexReplace} from './string/static_regex_replace';\n// tslint:disable-next-line:variable-name\nconst string = {\n stringNGrams,\n stringSplit,\n stringToHashBucketFast,\n staticRegexReplace,\n};\n\n// Second level exports.\nexport {image, linalg, losses, spectral, fused, signal, sparse, string};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OptimizerConstructors} from './optimizers/optimizer_constructors';\n\nexport const train = OptimizerConstructors;\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nconst delayCallback: Function = (() => {\n if (typeof requestAnimationFrame !== 'undefined') {\n return requestAnimationFrame;\n } else if (typeof setImmediate !== 'undefined') {\n return setImmediate;\n }\n return (f: Function) => f(); // no delays\n})();\n\n/**\n * Returns a promise that resolves when a requestAnimationFrame has completed.\n *\n * On Node.js this uses setImmediate instead of requestAnimationFrame.\n *\n * This is simply a sugar method so that users can do the following:\n * `await tf.nextFrame();`\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nfunction nextFrame(): Promise {\n return new Promise(resolve => delayCallback(() => resolve()));\n}\n\nexport {nextFrame};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\nexport function assertParamsConsistent(shapes: number[][], axis: number) {\n const rank = shapes[0].length;\n shapes.forEach((shape, i) => {\n util.assert(\n shape.length === rank,\n () =>\n `Error in concat${rank}D: rank of tensors[${i}] must be the same ` +\n `as the rank of the rest (${rank})`);\n });\n\n util.assert(\n axis >= 0 && axis < rank,\n () => `Error in concat${rank}D: axis must be between 0 and ${rank - 1}.`);\n\n const firstShape = shapes[0];\n shapes.forEach((shape, i) => {\n for (let r = 0; r < rank; r++) {\n util.assert(\n (r === axis) || (shape[r] === firstShape[r]),\n () => `Error in concat${rank}D: Shape of tensors[${i}] (${shape}) ` +\n `does not match the shape of the rest (${firstShape}) ` +\n `along the non-concatenated axis ${i}.`);\n }\n });\n}\n\nexport function computeOutShape(shapes: number[][], axis: number): number[] {\n const outputShape = shapes[0].slice();\n for (let i = 1; i < shapes.length; i++) {\n outputShape[axis] += shapes[i][axis];\n }\n return outputShape;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport enum RowPartitionType {\n FIRST_DIM_SIZE,\n VALUE_ROWIDS,\n ROW_LENGTHS,\n ROW_SPLITS,\n ROW_LIMITS,\n ROW_STARTS\n}\n\nexport function combineRaggedTensorToTensorShapes(\n raggedRank: number, shape: number[], valueShape: number[]) {\n // Test for consistency of valueShape and shape specified.\n // If shape is unspecified and valueShape is specified, then copy\n // over the size from the valueShape dimension.\n\n let outputShape: number[] = new Array();\n if (valueShape == null && shape == null) {\n return outputShape;\n }\n\n if (shape == null) {\n // Here, value_shape must be of known size.\n while (outputShape.length < raggedRank + valueShape.length) {\n outputShape.push(-1);\n }\n } else {\n outputShape = shape.slice();\n }\n if (valueShape == null) {\n return outputShape;\n }\n // At this point, valueShape and output_shape have known ranks.\n if (raggedRank + valueShape.length !== outputShape.length) {\n throw new Error(\n `rt input.shape and shape=${shape} are incompatible: rt input.rank = ${\n raggedRank +\n valueShape.length}, but shape.rank = ${outputShape.length}`);\n }\n\n for (let i = 1; i < valueShape.length; ++i) {\n const valueDim = valueShape[i];\n const outputShapeDimIndex =\n outputShape[outputShape.length - valueShape.length + i];\n const outputShapeDim = outputShape[outputShapeDimIndex];\n\n if (valueDim >= 0) {\n if (outputShapeDim >= 0) {\n if (outputShapeDim !== valueDim) {\n throw new Error(`rt input.shape and shape=${\n shape} are incompatible: rt input.shape[${i + raggedRank}] = ${\n valueDim} but shape[${i + raggedRank}] = ${outputShapeDim}`);\n }\n } else {\n outputShape[outputShapeDimIndex] = valueDim;\n }\n }\n }\n return outputShape;\n}\n\nexport function getRowPartitionTypesHelper(rowPartitionTypeStrings: string[]) {\n const stringToType = {\n 'FIRST_DIM_SIZE': RowPartitionType.FIRST_DIM_SIZE,\n 'VALUE_ROWIDS': RowPartitionType.VALUE_ROWIDS,\n 'ROW_LENGTHS': RowPartitionType.ROW_LENGTHS,\n 'ROW_SPLITS': RowPartitionType.ROW_SPLITS,\n 'ROW_LIMITS': RowPartitionType.ROW_LIMITS,\n 'ROW_STARTS': RowPartitionType.ROW_STARTS\n };\n\n const result: RowPartitionType[] = [];\n for (const typeStr of rowPartitionTypeStrings) {\n if (typeStr in stringToType) {\n result.push(stringToType[typeStr as keyof typeof stringToType]);\n } else {\n break;\n }\n }\n\n return result;\n}\n\nexport function getRaggedRank(rowPartitionTypes: RowPartitionType[]) {\n if (rowPartitionTypes.length === 0) {\n return 0;\n }\n if (rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {\n return rowPartitionTypes.length - 1;\n }\n return rowPartitionTypes.length;\n}\n\nexport function validateDefaultValueShape(\n defaultValueShape: number[], valueShape: number[]) {\n if (defaultValueShape == null || valueShape == null) {\n return;\n }\n\n const defaultNDims = defaultValueShape.length;\n const valuesNDims = valueShape.length;\n if (defaultNDims >= valuesNDims) {\n throw new Error(`defaultValue.shape=${\n defaultValueShape} and ragged tensor flatValues.shape=${\n valueShape}, are incompatible: defaultValue.rank = ${\n defaultNDims} must be less than ragged tensor input flatValues.rank = ${\n valuesNDims})`);\n }\n for (let i = 0; i < Math.min(defaultNDims, valuesNDims - 1); ++i) {\n const defaultDim = defaultValueShape[i];\n const valueDim = valueShape[i + 1];\n if (defaultDim >= 0 && valueDim >= 0 && defaultDim !== 1 &&\n defaultDim !== valueDim) {\n throw new Error(`defaultValue.shape=${\n defaultValueShape}, and ragged tensor input flatValues.shape=${\n valueShape} are incompatible: defaultValue.shape[${\n i - defaultValueShape.length}] = ${\n defaultDim} but ragged tensor input.flatValues.shape[${\n i - defaultValueShape.length}] = ${valueDim}`);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Inputs of size above this threshold will be parallelized by calling multiple\n * shader programs.\n */\nimport {nearestDivisor} from '../util';\n\nexport const PARALLELIZE_THRESHOLD = 30;\n\nexport interface ReduceInfo {\n windowSize: number;\n batchSize: number;\n inSize: number;\n outSize: number;\n}\n\nexport function computeOptimalWindowSize(inSize: number): number {\n if (inSize <= PARALLELIZE_THRESHOLD) {\n return inSize;\n }\n return nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Returns the image center in pixels.\nexport function getImageCenter(\n center: number|[number, number], imageHeight: number,\n imageWidth: number): [number, number] {\n const centerX =\n imageWidth * (typeof center === 'number' ? center : center[0]);\n const centerY =\n imageHeight * (typeof center === 'number' ? center : center[1]);\n return [centerX, centerY];\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Gets the new shape of the input Tensor after it's been reshaped\n * to:\n * [blockShape[0], ..., blockShape[M-1], batch / prod(blockShape),\n * inputShape[1], ..., inputShape[N-1]]\n *\n * See step 1: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getReshaped(\n inputShape: number[], blockShape: number[], prod: number,\n batchToSpace = true): number[] {\n let reshaped: number[] = [];\n if (batchToSpace) {\n reshaped = reshaped.concat(blockShape.slice(0));\n reshaped.push(inputShape[0] / prod);\n reshaped = reshaped.concat(inputShape.slice(1));\n } else {\n reshaped = reshaped.concat(inputShape[0]);\n const spatialLength = blockShape.length;\n for (let i = 0; i < spatialLength; ++i) {\n reshaped =\n reshaped.concat([inputShape[i + 1] / blockShape[i], blockShape[i]]);\n }\n reshaped = reshaped.concat(inputShape.slice(spatialLength + 1));\n }\n return reshaped;\n}\n\n/**\n * Gets the permutation that will transpose the dimensions of the\n * reshaped tensor to shape:\n *\n * [batch / prod(block_shape),inputShape[1], blockShape[0], ...,\n * inputShape[M], blockShape[M-1],inputShape[M+1], ..., inputShape[N-1]]\n *\n * see step 2: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getPermuted(\n reshapedRank: number, blockShapeRank: number,\n batchToSpace = true): number[] {\n const permuted = [];\n if (batchToSpace) {\n permuted.push(blockShapeRank);\n for (let i = blockShapeRank + 1; i < reshapedRank; ++i) {\n if (i <= 2 * blockShapeRank) {\n permuted.push(i);\n permuted.push(i - (blockShapeRank + 1));\n } else {\n permuted.push(i);\n }\n }\n } else {\n const permutedBeforeBatch = [];\n const permutedAfterBatch = [];\n for (let i = 1; i < reshapedRank; ++i) {\n if (i >= blockShapeRank * 2 + 1 || i % 2 === 1) {\n permutedAfterBatch.push(i);\n } else {\n permutedBeforeBatch.push(i);\n }\n }\n permuted.push(...permutedBeforeBatch);\n permuted.push(0);\n permuted.push(...permutedAfterBatch);\n }\n return permuted;\n}\n\n/**\n * Gets the shape of the reshaped and permuted input Tensor before any cropping\n * is applied. The new shape will be:\n *\n * [batch / prod(blockShape),inputShape[1] * blockShape[0], ...,\n * inputShape[M] * blockShape[M-1],inputShape[M+1], ..., inputShape[N-1]]\n *\n * See step 3: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getReshapedPermuted(\n inputShape: number[], blockShape: number[], prod: number,\n batchToSpace = true): number[] {\n const reshapedPermuted = [];\n\n if (batchToSpace) {\n reshapedPermuted.push(inputShape[0] / prod);\n } else {\n reshapedPermuted.push(inputShape[0] * prod);\n }\n\n for (let i = 1; i < inputShape.length; ++i) {\n if (i <= blockShape.length) {\n if (batchToSpace) {\n reshapedPermuted.push(blockShape[i - 1] * inputShape[i]);\n } else {\n reshapedPermuted.push(inputShape[i] / blockShape[i - 1]);\n }\n } else {\n reshapedPermuted.push(inputShape[i]);\n }\n }\n\n return reshapedPermuted;\n}\n\n/**\n * Converts the crops argument into the beginning coordinates of a slice\n * operation.\n */\nexport function getSliceBeginCoords(\n crops: number[][], blockShape: number): number[] {\n const sliceBeginCoords = [0];\n for (let i = 0; i < blockShape; ++i) {\n sliceBeginCoords.push(crops[i][0]);\n }\n return sliceBeginCoords;\n}\n\n/**\n * Converts the crops argument into the size of a slice operation. When\n * combined with getSliceBeginCoords this function allows the reshaped and\n * permuted Tensor to be cropped to its final output shape of:\n *\n * inputShape[1] * blockShape[0] - crops[0,0] - crops[0,1], ...,\n * inputShape[M] * blockShape[M-1] -crops[M-1,0] -\n * crops[M-1,1],inputShape[M+1], ..., inputShape[N-1]]\n *\n * See step 4: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getSliceSize(\n uncroppedShape: number[], crops: number[][], blockShape: number): number[] {\n const sliceSize = uncroppedShape.slice(0, 1);\n for (let i = 0; i < blockShape; ++i) {\n sliceSize.push(uncroppedShape[i + 1] - crops[i][0] - crops[i][1]);\n }\n\n return sliceSize;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const SELU_SCALEALPHA = 1.7580993408473768599402175208123;\nexport const SELU_SCALE = 1.0507009873554804934193349852946;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const ERF_P = 0.3275911;\nexport const ERF_A1 = 0.254829592;\nexport const ERF_A2 = -0.284496736;\nexport const ERF_A3 = 1.421413741;\nexport const ERF_A4 = -1.453152027;\nexport const ERF_A5 = 1.061405429;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray} from '../types';\n/**\n * Merges real and imaginary Float32Arrays into a single complex Float32Array.\n *\n * The memory layout is interleaved as follows:\n * real: [r0, r1, r2]\n * imag: [i0, i1, i2]\n * complex: [r0, i0, r1, i1, r2, i2]\n *\n * This is the inverse of splitRealAndImagArrays.\n *\n * @param real The real values of the complex tensor values.\n * @param imag The imag values of the complex tensor values.\n * @returns A complex tensor as a Float32Array with merged values.\n */\nexport function mergeRealAndImagArrays(\n real: Float32Array, imag: Float32Array): Float32Array {\n if (real.length !== imag.length) {\n throw new Error(\n `Cannot merge real and imag arrays of different lengths. real:` +\n `${real.length}, imag: ${imag.length}.`);\n }\n const result = new Float32Array(real.length * 2);\n for (let i = 0; i < result.length; i += 2) {\n result[i] = real[i / 2];\n result[i + 1] = imag[i / 2];\n }\n return result;\n}\n\n/**\n * Splits a complex Float32Array into real and imag parts.\n *\n * The memory layout is interleaved as follows:\n * complex: [r0, i0, r1, i1, r2, i2]\n * real: [r0, r1, r2]\n * imag: [i0, i1, i2]\n *\n * This is the inverse of mergeRealAndImagArrays.\n *\n * @param complex The complex tensor values.\n * @returns An object with real and imag Float32Array components of the complex\n * tensor.\n */\nexport function splitRealAndImagArrays(complex: Float32Array):\n {real: Float32Array, imag: Float32Array} {\n const real = new Float32Array(complex.length / 2);\n const imag = new Float32Array(complex.length / 2);\n for (let i = 0; i < complex.length; i += 2) {\n real[i / 2] = complex[i];\n imag[i / 2] = complex[i + 1];\n }\n return {real, imag};\n}\n\n/**\n * Extracts even indexed complex values in the given array.\n * @param complex The complex tensor values\n */\nexport function complexWithEvenIndex(complex: Float32Array):\n {real: Float32Array, imag: Float32Array} {\n const len = Math.ceil(complex.length / 4);\n const real = new Float32Array(len);\n const imag = new Float32Array(len);\n for (let i = 0; i < complex.length; i += 4) {\n real[Math.floor(i / 4)] = complex[i];\n imag[Math.floor(i / 4)] = complex[i + 1];\n }\n return {real, imag};\n}\n\n/**\n * Extracts odd indexed 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(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(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(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 '../tensor_info';\nimport {Tensor} from '../tensor';\nimport {assert} from '../util';\n\n/**\n * Prepare the split size array. When the input is a number, the axis is evenly\n * divided among the split size. When the input contains the negative value, the\n * rest of the axis is allocated toward that.\n */\nexport function prepareSplitSize(\n x: Tensor|TensorInfo, numOrSizeSplits: number[]|number,\n axis = 0): number[] {\n let splitSizes = [];\n if (typeof (numOrSizeSplits) === 'number') {\n assert(\n x.shape[axis] % numOrSizeSplits === 0,\n () => 'Number of splits must evenly divide the axis.');\n splitSizes =\n new Array(numOrSizeSplits).fill(x.shape[axis] / numOrSizeSplits);\n } else {\n const numOfNegs = numOrSizeSplits.reduce((count, value) => {\n if (value === -1) {\n count += 1;\n }\n return count;\n }, 0);\n assert(\n numOfNegs <= 1,\n () => 'There should be only one negative value in split array.');\n const negIndex = numOrSizeSplits.indexOf(-1);\n // Allow the number of split array to be -1, which indicates the rest\n // of dimension is allocated to that split.\n if (negIndex !== -1) {\n const total = numOrSizeSplits.reduce((a, b) => b > 0 ? a + b : a);\n numOrSizeSplits[negIndex] = x.shape[axis] - total;\n }\n assert(\n x.shape[axis] === numOrSizeSplits.reduce((a, b) => a + b),\n () => 'The sum of sizes must match the size of the axis dimension.');\n splitSizes = numOrSizeSplits;\n }\n\n return splitSizes;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Generates sparse fill empty rows indices, dense shape mismatch error message.\n *\n * @param indicesLength The first dimension of indices.\n */\nexport function getSparseFillEmptyRowsIndicesDenseShapeMismatch(\n indicesLength: number) {\n return `Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${indicesLength}`;\n}\n\n/**\n * Generates sparse fill empty rows negative index error message.\n *\n * @param index The index with a negative value.\n * @param value The negative value.\n */\nexport function getSparseFillEmptyRowsNegativeIndexErrorMessage(\n index: number, value: number) {\n return `indices(${index}, 0) is invalid: ${value} < 0`;\n}\n\n/**\n * Generates sparse fill empty rows out of range index error message.\n *\n * @param index The index with an out of range value.\n * @param value The out of range value.\n * @param limit The upper limit for indices.\n */\nexport function getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(\n index: number, value: number, limit: number) {\n return `indices(${index}, 0) is invalid: ${value} >= ${limit}`;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {sizeFromShape} from '../../util';\n\n/**\n * Generates sparse reshape multiple negative 1 output dimension error message.\n *\n * @param dim1 The first dimension with a negative 1 value.\n * @param dim2 The second dimension with a negative 1 value.\n */\nexport function getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(\n dim1: number, dim2: number) {\n return `only one output dimension may be -1, not both ${dim1} and ${dim2}`;\n}\n\n/**\n * Generates sparse reshape negative output dimension error message.\n *\n * @param dim The dimension with a negative value.\n * @param value The negative value.\n */\nexport function getSparseReshapeNegativeOutputDimErrorMessage(\n dim: number, value: number) {\n return `size ${dim} must be non-negative, not ${value}`;\n}\n\n/**\n * Generates sparse reshape empty tensor zero output dimension error message.\n *\n */\nexport function getSparseReshapeEmptyTensorZeroOutputDimErrorMessage() {\n return 'reshape cannot infer the missing input size for an empty tensor ' +\n 'unless all specified input sizes are non-zero';\n}\n\n/**\n * Generates sparse reshape input output multiple mismatch error message.\n *\n * @param inputShape the input shape.\n * @param outputShape the requested output shape.\n */\nexport function getSparseReshapeInputOutputMultipleErrorMessage(\n inputShape: number[], outputShape: number[]) {\n const inputSize = sizeFromShape(inputShape);\n const outputSize = sizeFromShape(outputShape);\n return `Input to reshape is a SparseTensor with ${inputSize}\n dense values, but the requested shape requires a multiple of ${\n outputSize}. inputShape=${inputShape} outputShape= ${outputShape}`;\n}\n\n/**\n * Generates sparse reshape input output inequality error message.\n *\n * @param inputShape the input shape.\n * @param outputShape the requested output shape.\n */\nexport function getSparseReshapeInputOutputMismatchErrorMessage(\n inputShape: number[], outputShape: number[]) {\n const inputSize = sizeFromShape(inputShape);\n const outputSize = sizeFromShape(outputShape);\n return `Input to reshape is a tensor with ${\n inputSize} dense values, but the requested shape has ${\n outputSize}. inputShape=${inputShape} outputShape=${outputShape}`;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Generates sparse segment reduction negative segment ids error message.\n *\n */\nexport function getSparseSegmentReductionNegativeSegmentIdsErrorMessage() {\n return `segment ids must be >= 0`;\n}\n\n/**\n * Generates sparse segment reduction non increasing segment ids error message.\n *\n */\nexport function getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage() {\n return `segment ids are not increasing`;\n}\n\n/**\n * Generates sparse segment reduction segment id out of range error message.\n *\n * @param segmentId The segment id index that is out of range.\n * @param outputRows Upper bound of valid segment id values.\n */\nexport function getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(\n segmentId: number, outputRows: number) {\n return `Segment id ${segmentId} out of range [0, ${\n outputRows}), possibly because segmentIds input is not sorted.`;\n}\n\n/**\n * Generates sparse segment reduction input indice out of range error message.\n *\n * @param index The index that holds the out of range value.\n * @param indexValue The value that is out of range.\n * @param inputRows Upper bound of valid index values.\n */\nexport function getSparseSegmentReductionIndicesOutOfRangeErrorMessage(\n index: number, indexValue: number, inputRows: number) {\n return `Bad: indices[${index}] == ${indexValue} out of range [0, ${\n inputRows})`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { TensorInfo } from '../tensor_info';\nimport {nearestDivisor} from '../util';\n\nimport {PARALLELIZE_THRESHOLD} from './reduce_util';\n\nexport interface SegOpInfo {\n windowSize: number;\n batchSize: number;\n inSize: number;\n numSegments: number;\n}\n\nexport function segOpComputeOptimalWindowSize(\n inSize: number, numSegments: number): number {\n let done = false;\n let res;\n\n if (inSize <= PARALLELIZE_THRESHOLD) {\n res = inSize;\n done = true;\n } else {\n res = nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));\n }\n\n while (!done) {\n if (res > numSegments || res === inSize) {\n done = true;\n } else {\n res = nearestDivisor(inSize, res + 1);\n }\n }\n return res;\n}\n\nexport function computeOutShape(\n aShape: number[], axis: number, numSegments: number): number[] {\n const outShape = [];\n const rank = aShape.length;\n for (let dim = 0; dim < rank; dim++) {\n if (dim !== axis) {\n outShape.push(aShape[dim]);\n } else {\n outShape.push(numSegments);\n }\n }\n return outShape;\n}\n\nexport interface GatherOpShapeInfo {\n batchSize: number;\n sliceSize: number;\n outerSize: number;\n dimSize: number;\n outputShape: number[];\n}\n\nexport function collectGatherOpShapeInfo(\n x: TensorInfo, indices: TensorInfo, axis: number,\n batchDims: number): GatherOpShapeInfo {\n const indicesRank = indices.shape.length;\n const xRank = x.shape.length;\n\n if (batchDims !== 0) {\n if (batchDims < -indicesRank || batchDims > indicesRank) {\n throw new Error(`Expect batchDims in the range of [-${indicesRank}, ${\n indicesRank}], but got ${batchDims}`);\n }\n }\n\n if (batchDims < 0) {\n batchDims += indicesRank;\n }\n\n if (batchDims > xRank) {\n throw new Error(`batchDims (${batchDims}) must be less than rank(x) (\n ${xRank}).`);\n }\n\n if (axis < batchDims) {\n throw new Error(`batchDims (${\n batchDims}) must be less than or equal to axis (${axis}).`);\n }\n\n for (let i = 0; i < batchDims; ++i) {\n if (x.shape[i] !== indices.shape[i]) {\n throw new Error(\n `x.shape[${i}]: ${x.shape[i]} should be equal to indices.shape[${\n i}]: ${indices.shape[i]}.`);\n }\n }\n const dimSize = x.shape[axis];\n\n const outputShape: number[] = [];\n let batchSize = 1;\n let outerSize = 1;\n let sliceSize = 1;\n\n for (let i = 0; i < batchDims; ++i) {\n outputShape.push(x.shape[i]);\n batchSize *= x.shape[i];\n }\n\n for (let i = batchDims; i < axis; i++) {\n outputShape.push(x.shape[i]);\n outerSize *= x.shape[i];\n }\n\n for (let i = batchDims; i < indicesRank; i++) {\n outputShape.push(indices.shape[i]);\n }\n\n for (let i = axis + 1; i < xRank; i++) {\n outputShape.push(x.shape[i]);\n sliceSize *= x.shape[i];\n }\n\n return {batchSize, sliceSize, outerSize, dimSize, outputShape};\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {decodeString, encodeString} from '../util';\n\n// Utilities needed by backend consumers of tf-core.\nexport * from '../ops/axis_util';\nexport * from '../ops/broadcast_util';\nexport * from '../ops/concat_util';\nexport * from '../ops/conv_util';\nexport * from '../ops/fused_util';\nexport * from '../ops/fused_types';\nexport * from '../ops/ragged_to_dense_util';\nexport * from '../ops/reduce_util';\n\nimport * as slice_util from '../ops/slice_util';\nexport {slice_util};\n\nexport {BackendValues, TypedArray, upcastType, PixelData} from '../types';\nexport {MemoryInfo, TimingInfo} from '../engine';\nexport * from '../ops/rotate_util';\nexport * from '../ops/array_ops_util';\nexport * from '../ops/gather_nd_util';\nexport * from '../ops/scatter_nd_util';\nexport * from '../ops/selu_util';\nexport * from '../ops/fused_util';\nexport * from '../ops/erf_util';\nexport * from '../log';\nexport * from '../backends/complex_util';\nexport * from '../backends/einsum_util';\nexport * from '../ops/split_util';\nexport * from '../ops/sparse/sparse_fill_empty_rows_util';\nexport * from '../ops/sparse/sparse_reshape_util';\nexport * from '../ops/sparse/sparse_segment_reduction_util';\n\nimport * as segment_util from '../ops/segment_util';\nexport {segment_util};\n\nexport function fromUint8ToStringArray(vals: Uint8Array[]) {\n try {\n // Decode the bytes into string.\n return vals.map(val => decodeString(val));\n } catch (err) {\n throw new Error(\n `Failed to decode encoded string bytes into utf-8, error: ${err}`);\n }\n}\n\nexport function fromStringArrayToUint8(strings: string[]) {\n return strings.map(s => encodeString(s));\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code.\nimport './base_side_effects';\n\n// TODO(mattSoulanille): Move this to base_side_effects.ts\n// It is here for now because custom bundles need to avoid calling it, and they\n// only replace the index.js file, not the base_side_effects file.\nimport {registerOptimizers} from './optimizers/register_optimizers';\nregisterOptimizers();\n\n// All exports from this package should be in base.\nexport * from './base';\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {checkPadOnDimRoundingMode} from './conv_util';\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_(\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 checkPadOnDimRoundingMode('avgPool3dGrad', pad, dimRoundingMode);\n const inputs: AvgPool3DGradInputs = {dy: dy5D, input: input5D};\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 unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n\n return res;\n}\n\nexport const avgPool3dGrad = /* @__PURE__ */ 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 unknown 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_(\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 unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo4D) {\n return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n }\n return res;\n}\n\nexport const avgPoolGrad = /* @__PURE__ */ 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 unknown 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 unknown 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 unknown 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 unknown 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 unknown 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} =\n attrs as unknown 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 unknown 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_(\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 unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor5D;\n}\n\nexport const conv3DBackpropFilter = /* @__PURE__ */ 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 unknown 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 =\n attrs as unknown 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 unknown as DepthwiseConv2dNativeAttrs;\n const $dilations = dilations == null ? [1, 1] as[number,number] : 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 conv_util.checkPadOnDimRoundingMode(\n 'depthwiseConv2d', pad, dimRoundingMode);\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,\n inputInputs as unknown as NamedTensorMap, attrs),\n filter: () => ENGINE.runKernel(\n Dilation2DBackpropFilter,\n filterInputs as unknown 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,\n inputs as unknown 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: (\n dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const {varianceEpsilon} = attrs as unknown 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 {stack} from '../ops/stack';\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, batchDims} = attrs as unknown as GatherV2Attrs;\n\n const parsedAxis = parseAxisParam(axis, x.shape)[0];\n\n const derXBatch = (x: Tensor, indices: Tensor, dy: Tensor) => {\n return (): Tensor => {\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],\n 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 const invertTransposeDims = getUndoAxesPermutation(transposeDims);\n paramsGrad = transpose(paramsGrad, invertTransposeDims);\n return paramsGrad;\n };\n };\n\n if (batchDims === 1) {\n const batchSize = x.shape[0];\n const xBatch = x.split(batchSize, 0);\n const derXBatched = () => {\n const stacked = stack(\n xBatch.map((x, i) => {\n return derXBatch(x, indices.slice(i,1), dy.slice(i,1))();\n }));\n return stacked.reshape(x.shape);\n };\n return {x: derXBatched, indices: () => indices};\n } else {\n return {x: derXBatch(x, indices, dy), indices: () => indices};\n }\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 unknown 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 unknown 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_(\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 unknown as NamedTensorMap,\n attrs as unknown 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 unknown 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(\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 unknown 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 {checkPadOnDimRoundingMode} from './conv_util';\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_(\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 checkPadOnDimRoundingMode('maxPool3dGrad', pad, dimRoundingMode);\n const inputs:\n MaxPool3DGradInputs = {dy: dy5D, input: input5D, output: output5D};\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 unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as T;\n\n if (reshapedTo5D) {\n return reshape(\n res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n T;\n }\n\n return res;\n}\n\nexport const maxPool3dGrad = /* @__PURE__ */ 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 unknown 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 * as conv_util 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|conv_util.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 conv_util.checkPadOnDimRoundingMode('maxPoolGrad', pad, dimRoundingMode);\n const inputs: MaxPoolGradInputs = {dy: $dy, input: $input, output: $output};\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 unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const maxPoolGrad = /* @__PURE__ */ 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 unknown 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 {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 {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 2022 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '../base';\nimport {Prod, ProdAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {cumprod} from '../ops/cumprod';\nimport {mul} from '../ops/mul';\nimport {reshape} from '../ops/reshape';\nimport {transpose} from '../ops/transpose';\nimport {Tensor} from '../tensor';\n\n// Gradient for product operation on a single axis.\nfunction prodGradFn_(x: Tensor, dy: Tensor, axis: number): Tensor {\n // The gradient tensor (dy) has a set of axes removed, so we create re-shaped\n // versions (of size 1) for the removed axis; this supports broadcasting over\n // those dimensions.\n const expandedYShape = x.shape.slice();\n expandedYShape[axis] = 1;\n\n // The actual gradient computation.\n const expandedDy = reshape(dy, expandedYShape);\n const xCumProd = cumprod(x, axis, true, false);\n const xCumRevProd = cumprod(x, axis, true, true);\n const dx = mul(xCumProd, xCumRevProd);\n return mul(expandedDy, dx);\n}\n\n// Support gradients when the product is done on many axes at once.\n// This done py pushing all the axes on which the product is applied into a\n// single axis.\nfunction prodsGradFn_(x: Tensor, dy: Tensor, axis: number[]): Tensor {\n // Move all axes for doing prod over to the end of the tensor.\n const xRank = x.shape.length;\n const finalProdAxis = xRank - axis.length;\n const xPermutation = backend_util.getAxesPermutation(axis, xRank);\n let permutedX = x;\n if (xPermutation != null) {\n permutedX = transpose(x, xPermutation);\n }\n\n // Reshape all the prod dimensions into a single one, and do compute prod\n // gradients on that.\n const newShape = permutedX.shape.slice();\n const removedShape = newShape.splice(xRank - axis.length, axis.length);\n const endPartShape = removedShape.reduce((p, c) => p * c, 1);\n newShape.push(endPartShape);\n const reshapedPermutedX = permutedX.reshape(newShape);\n let prodGrad = prodGradFn_(reshapedPermutedX, dy, finalProdAxis);\n\n // Undo the re-shaping now we have the dx vector, and permute back to\n // original axes order.\n prodGrad = prodGrad.reshape(permutedX.shape);\n if (xPermutation != null) {\n const undoPermutation = backend_util.getUndoAxesPermutation(xPermutation);\n prodGrad = transpose(prodGrad, undoPermutation);\n }\n return prodGrad;\n}\n\n// Running example:\n// [\n// [\n// [3.0, 4.0],\n// [5.0, 6.0],\n// [7.0, 8.0]\n// ],\n// [\n// [3.0, 5.0],\n// [0.0, 6.0],\n// [5.0, 6.0]\n// ]\n// ]\n//\nexport const prodGradConfig: GradConfig = {\n kernelName: Prod,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor|Tensor[], saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {axis} = (attrs as {}) as ProdAttrs;\n let axisArr = [] as number[];\n if (axis === undefined || axis === null) {\n axisArr = x.shape.map((_, i) => i);\n } else if (typeof axis === 'number') {\n axisArr = [axis];\n } else {\n axisArr = axis;\n }\n return {x: () => prodsGradFn_(x, dy as Tensor, axisArr)};\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 unknown 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 unknown 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 {ZerosLike} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const zerosLikeGradConfig: GradConfig = {\n kernelName: ZerosLike,\n gradFunc: (dy: Tensor) => {\n return {x: () => zerosLike(dy)};\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {absGradConfig} from './gradients/Abs_grad';\nimport {acosGradConfig} from './gradients/Acos_grad';\nimport {acoshGradConfig} from './gradients/Acosh_grad';\nimport {addGradConfig} from './gradients/Add_grad';\nimport {addNGradConfig} from './gradients/AddN_grad';\nimport {argMaxGradConfig} from './gradients/ArgMax_grad';\nimport {argMinGradConfig} from './gradients/ArgMin_grad';\nimport {asinGradConfig} from './gradients/Asin_grad';\nimport {asinhGradConfig} from './gradients/Asinh_grad';\nimport {atan2GradConfig} from './gradients/Atan2_grad';\nimport {atanGradConfig} from './gradients/Atan_grad';\nimport {atanhGradConfig} from './gradients/Atanh_grad';\nimport {avgPool3DGradConfig} from './gradients/AvgPool3D_grad';\nimport {avgPoolGradConfig} from './gradients/AvgPool_grad';\nimport {batchMatMulGradConfig} from './gradients/BatchMatMul_grad';\nimport {batchToSpaceNDGradConfig} from './gradients/BatchToSpaceND_grad';\nimport {broadcastToGradConfig} from './gradients/BroadcastTo_grad';\nimport {castGradConfig} from './gradients/Cast_grad';\nimport {ceilGradConfig} from './gradients/Ceil_grad';\nimport {clipByValueGradConfig} from './gradients/ClipByValue_grad';\nimport {complexAbsGradConfig} from './gradients/ComplexAbs_grad';\nimport {concatGradConfig} from './gradients/Concat_grad';\nimport {conv2DGradConfig} from './gradients/Conv2D_grad';\nimport {conv2DBackpropInputGradConfig} from './gradients/Conv2DBackpropInput_grad';\nimport {conv3DGradConfig} from './gradients/Conv3D_grad';\nimport {cosGradConfig} from './gradients/Cos_grad';\nimport {coshGradConfig} from './gradients/Cosh_grad';\nimport {cumsumGradConfig} from './gradients/Cumsum_grad';\nimport {depthwiseConv2dNativeGradConfig} from './gradients/DepthwiseConv2dNative_grad';\nimport {dilation2dGradConfig} from './gradients/Dilation2D_grad';\nimport {eluGradConfig} from './gradients/Elu_grad';\nimport {erfGradConfig} from './gradients/Erf_grad';\nimport {expGradConfig} from './gradients/Exp_grad';\nimport {expandDimsGradConfig} from './gradients/ExpandDims_grad';\nimport {expm1GradConfig} from './gradients/Expm1_grad';\nimport {floorGradConfig} from './gradients/Floor_grad';\nimport {floorDivGradConfig} from './gradients/FloorDiv_grad';\nimport {fusedBatchNormGradConfig} from './gradients/FusedBatchNorm_grad';\nimport {gatherGradConfig} from './gradients/GatherV2_grad';\nimport {greaterEqualGradConfig} from './gradients/GreaterEqual_grad';\nimport {identityGradConfig} from './gradients/Identity_grad';\nimport {isFiniteGradConfig} from './gradients/IsFinite_grad';\nimport {isInfGradConfig} from './gradients/IsInf_grad';\nimport {isNanGradConfig} from './gradients/IsNan_grad';\nimport {leakyReluGradConfig} from './gradients/LeakyRelu_grad';\nimport {log1pGradConfig} from './gradients/Log1p_grad';\nimport {logGradConfig} from './gradients/Log_grad';\nimport {logSoftmaxGradConfig} from './gradients/LogSoftmax_grad';\nimport {lrnGradConfig} from './gradients/LRN_grad';\nimport {maxGradConfig} from './gradients/Max_grad';\nimport {maximumGradConfig} from './gradients/Maximum_grad';\nimport {maxPool3DGradConfig} from './gradients/MaxPool3D_grad';\nimport {maxPoolGradConfig} from './gradients/MaxPool_grad';\nimport {meanGradConfig} from './gradients/Mean_grad';\nimport {minGradConfig} from './gradients/Min_grad';\nimport {minimumGradConfig} from './gradients/Minimum_grad';\nimport {mirrorPadGradConfig} from './gradients/MirrorPad_grad';\nimport {modGradConfig} from './gradients/Mod_grad';\nimport {multiplyGradConfig} from './gradients/Multiply_grad';\nimport {negGradConfig} from './gradients/Neg_grad';\nimport {oneHotGradConfig} from './gradients/OneHot_grad';\nimport {onesLikeGradConfig} from './gradients/OnesLike_grad';\nimport {packGradConfig} from './gradients/Pack_grad';\nimport {padV2GradConfig} from './gradients/PadV2_grad';\nimport {powGradConfig} from './gradients/Pow_grad';\nimport {preluGradConfig} from './gradients/Prelu_grad';\nimport {prodGradConfig} from './gradients/Prod_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 prodGradConfig,\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 {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 {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 unknown 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 unknown 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 {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 unknown 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 */\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 {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 unknown 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 unknown as NamedTensorMap,\n attrs) as 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 unknown 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 */\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 unknown 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 unknown 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 {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 unknown 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 unknown 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 unknown 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(x: T, indices: Tensor1D) {\n // Helper function for unsorted segment ops. Gathers params for\n // positive segment ids and gathers 0 for inputs with negative segment id.\n // Mirrors _GatherDropNegatives from tensorflow/python/ops/math_grad.py\n const zeroClippedIndices = maximum(indices, zerosLike(indices));\n const gathered = gather(x, zeroClippedIndices as Tensor1D);\n let isPositive = greaterEqual(indices, scalar(0, 'int32'));\n const numIters = gathered.rank - isPositive.rank;\n for (let i = 0; i < numIters; ++i) {\n isPositive = expandDims(isPositive, i + 1);\n }\n isPositive = logicalAnd(isPositive, ones(gathered.shape, 'bool'));\n const zeroSlice = zerosLike(gathered);\n return where(isPositive, gathered, zeroSlice);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\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 {\n abs(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.abs = function(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 {\n acos(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.acos = function(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 {\n acosh(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.acosh = function(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 {\n add(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.add = function(\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 {\n all(this: T, axis?: number|number[], keepDims?: boolean):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.all = function(\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 {\n any(this: T, axis?: number|number[], keepDims?: boolean):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.any = function(\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 {\n argMax(axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.argMax = function(\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 {\n argMin(axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.argMin = function(\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 {\n asScalar(): 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(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 {\n asType(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(\n this: T, dtype: DataType): T {\n this.throwIfDisposed();\n return cast(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 {\n as1D(): 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 {\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 {\n as2D(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(\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 {\n as3D(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(\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 {\n as4D(\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(\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 {\n as5D(\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(\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 {\n asin(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.asin = function(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 {\n asinh(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.asinh = function(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 {\n atan(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.atan = function(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 {\n atan2(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.atan2 = function(\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 {\n atanh(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.atanh = function(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 {\n avgPool(\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(\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 {\n batchToSpaceND(blockShape: number[], crops: number[][]):\n Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.batchToSpaceND = function(\n blockShape: number[], crops: number[][]): Tensor {\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 {\n batchNorm(\n mean: Tensor|Tensor1D|TensorLike,\n variance: Tensor|Tensor1D|TensorLike,\n offset?: Tensor|Tensor1D|TensorLike,\n scale?: Tensor|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.batchNorm = function(\n mean: Tensor|Tensor1D|TensorLike,\n variance: Tensor|Tensor1D|TensorLike,\n offset?: Tensor|Tensor1D|TensorLike,\n scale?: Tensor|Tensor1D|TensorLike,\n varianceEpsilon?: number): Tensor {\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 {\n broadcastTo(shape: ShapeMap[R]): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.broadcastTo = function(\n shape: ShapeMap[R]): Tensor {\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 {\n cast(dtype: DataType): T;\n }\n}\n\ngetGlobalTensorClass().prototype.cast = function(\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 {\n ceil(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.ceil = function(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 {\n clipByValue(min: number, max: number): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.clipByValue = function(\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 {\n concat(tensors: T|Array, axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.concat = function(\n x: T|Array, 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 {\n conv1d(\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(\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 {\n conv2dTranspose(\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(\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 {\n conv2d(\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(\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 {\n cos(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.cos = function(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 {\n cosh(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.cosh = function(this: T): T {\n this.throwIfDisposed();\n return cosh(this);\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { cumprod } from '../../ops/cumprod';\nimport { getGlobalTensorClass, Tensor } from '../../tensor';\nimport { Rank } from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor {\n cumprod(\n axis?: number,\n exclusive?: boolean,\n reverse?: boolean\n ): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.cumprod = function (\n axis?: number,\n exclusive?: boolean,\n reverse?: boolean\n): Tensor {\n this.throwIfDisposed();\n return cumprod(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 {cumsum} from '../../ops/cumsum';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor {\n cumsum(\n axis?: number, exclusive?: boolean, reverse?: boolean): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.cumsum = function(\n axis?: number, exclusive?: boolean, reverse?: boolean): Tensor {\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 {\n depthToSpace(\n blockSize: number, dataFormat: 'NHWC'|'NCHW'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.depthToSpace = function(\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 {\n depthwiseConv2d(\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(\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 {\n dilation2d(\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(\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 {\n divNoNan(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.divNoNan = function(\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 {\n div(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.div = function(\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 {\n dot(b: Tensor|TensorLike): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.dot = function(\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 {\n elu(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.elu = function(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 {\n equal(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.equal = function(\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 {\n erf(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.erf = function(this: T): T {\n this.throwIfDisposed();\n return erf(this);\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 {euclideanNorm} from '../../ops/euclidean_norm';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor {\n euclideanNorm(\n this: T, axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.euclideanNorm = function(\n this: T, axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return euclideanNorm(this, 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 */\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 {\n exp(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.exp = function(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 {\n expandDims(axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.expandDims = function(\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 {\n expm1(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.expm1 = function(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 {\n fft(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.fft = function(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 {\n flatten(): 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 {\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 {\n floor(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.floor = function(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 {\n floorDiv(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.floorDiv = function(\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 {\n gather(\n this: T, indices: Tensor|TensorLike, axis?: number,\n batchDims?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.gather = function(\n this: T, indices: Tensor|TensorLike, axis?: number, batchDims?: number): T {\n this.throwIfDisposed();\n return gather(this, indices, axis, batchDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n greaterEqual(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.greaterEqual = function(\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 {\n greater(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.greater = function(\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 {\n ifft(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.ifft = function(\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 {\n irfft(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.irfft = function(\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 {\n isFinite(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.isFinite = function(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 {\n isInf(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.isInf = function(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 {\n isNaN(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.isNaN = function(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 {\n leakyRelu(alpha: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.leakyRelu = function(\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 {\n lessEqual(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.lessEqual = function(\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 {\n less(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.less = function(\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 {\n localResponseNormalization(\n depthRadius?: number, bias?: number, alpha?: number, beta?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.localResponseNormalization =\n function(\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 {\n logSigmoid(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logSigmoid = function(\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 {\n logSoftmax(this: T, axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logSoftmax = function(\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 {\n logSumExp(\n this: T, axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logSumExp = function(\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 {\n log(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.log = function(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 {\n log1p(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.log1p = function(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 {\n logicalAnd(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalAnd = function(\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 {\n logicalNot(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalNot = function(): 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 {\n logicalOr(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalOr = function(\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 {\n logicalXor(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalXor = function(\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 {\n matMul(\n b: Tensor|TensorLike, transposeA?: boolean,\n transposeB?: boolean): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.matMul = function(\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 {\n maxPool(\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(\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 {\n max(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.max = function(\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 {\n maximum(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.maximum = function(\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 {\n mean(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mean = function(\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 {\n min(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.min = function(\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 {\n minimum(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.minimum = function(\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 {\n mirrorPad(\n paddings: Array<[number, number]>, mode: 'reflect'|'symmetric'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mirrorPad = function(\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 {\n mod(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mod = function(\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 {\n mul(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mul = function(\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 {\n neg(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.neg = function(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 {\n norm(\n ord?: number|'euclidean'|'fro', axis?: number|number[],\n keepDims?: boolean): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.norm = function(\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 {\n notEqual(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.notEqual = function(\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 {\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 {\n onesLike(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.onesLike = function(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 {\n pad(\n paddings: Array<[number, number]>, constantValue?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.pad = function(\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 {\n pool(\n windowShape: [number, number]|number, poolingType: 'avg'|'max',\n padding: 'valid'|'same'|number|ExplicitPadding,\n diationRate?: [number, number]|number,\n strides?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.pool = function(\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,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return pool(this, windowShape, poolingType, padding, dilationRate, strides,\n 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 {pow} from '../../ops/pow';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor {\n pow(exp: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.pow = function(\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 {\n prelu(alpha: T|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.prelu = function(\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 {\n prod(this: T, axis?: number|number[], keepDims?: boolean):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.prod = function(\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 {\n reciprocal(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.reciprocal = function(\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 {\n relu(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.relu = function(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 {\n relu6(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.relu6 = function(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 {\n reshapeAs(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(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 {\n reshape(shape: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.reshape = function(\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 {\n resizeBilinear(\n newShape2D: [number, number], alignCorners?: boolean,\n halfPixelCenters?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.resizeBilinear =\n function(\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 {\n resizeNearestNeighbor(\n newShape2D: [number, number], alignCorners?: boolean,\n halfFloatCenters?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.resizeNearestNeighbor =\n function(\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 {\n reverse(this: T, axis?: number|number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.reverse = function(\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 {\n rfft(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.rfft = function(\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 {\n round(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.round = function(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 {\n rsqrt(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.rsqrt = function(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 {\n selu(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.selu = function(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 {\n separableConv2d(\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(\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 {\n sigmoid(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sigmoid = function(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 {\n sign(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sign = function(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 {\n sin(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sin = function(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 {\n sinh(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sinh = function(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 {\n slice(\n this: T, begin: number|number[], size?: number|number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.slice = function(\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 {\n softmax(this: T, dim?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.softmax = function(\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 {\n softplus(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.softplus = function(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 {\n spaceToBatchND(blockShape: number[], paddings: number[][]):\n Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.spaceToBatchND = function(\n blockShape: number[], paddings: number[][]): Tensor {\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 {\n split(numOrSizeSplits: number[]|number, axis?: number):\n T[];\n }\n}\n\ngetGlobalTensorClass().prototype.split = function(\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 {\n sqrt(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sqrt = function(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 {\n square(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.square = function(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 {\n squaredDifference(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.squaredDifference = function(\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 {\n squeeze(axis?: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.squeeze = function(\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 {\n stack(x: Tensor|Tensor[], axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.stack = function(\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 {\n step(this: T, alpha?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.step = function(\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 {\n stridedSlice(\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(\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 {\n sub(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sub = function(\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 {\n sum(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sum = function(\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 {\n tan(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.tan = function(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 {\n tanh(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.tanh = function(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 {\n tile(b: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.tile = function(\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 {\n toBool(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(this: T):\n T {\n this.throwIfDisposed();\n return cast(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 {\n toFloat(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(this: T):\n T {\n this.throwIfDisposed();\n return cast(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 {\n toInt(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(this: T):\n T {\n this.throwIfDisposed();\n return cast(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 {\n topk(this: T, k?: number, sorted?: boolean):\n {values: T, indices: T};\n }\n}\n\ngetGlobalTensorClass().prototype.topk = function(\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 {\n transpose(perm?: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.transpose = function(\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 {\n unique(this: T, axis?: number): {values: T, indices: T};\n }\n}\n\ngetGlobalTensorClass().prototype.unique = function(\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 {\n unsortedSegmentSum(\n this: T, segmentIds: Tensor1D|TensorLike1D, numSegments: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.unsortedSegmentSum =\n function(\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 {\n unstack(axis?: number): T[];\n }\n}\n\ngetGlobalTensorClass().prototype.unstack = function(\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 {\n where(condition: Tensor|TensorLike, x: Tensor|TensorLike):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.where = function(\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 {\n zerosLike(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.zerosLike = function(\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\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 2022 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 * LruCache: A mapping from the String to T. If the number of the entries is\n * exceeding the `maxEntries`, the LruCache will delete the least recently\n * used entry.\n */\n\nexport class LruCache {\n private cache: Map;\n private maxEntries: number;\n\n constructor(maxEntries?: number) {\n this.maxEntries = maxEntries || 100;\n this.cache = new Map();\n }\n\n /**\n * Get the entry for the key and mark it as used recently.\n */\n public get(key: string): T {\n let entry: T;\n if (this.cache.has(key)) {\n entry = this.cache.get(key);\n this.cache.delete(key);\n this.cache.set(key, entry);\n }\n return entry;\n }\n\n /**\n * Put the entry into the cache. If the key already existed, mark the key as\n * used recently.\n */\n public put(key: string, value: T): void {\n if (this.cache.has(key)) {\n this.cache.delete(key);\n } else if (this.cache.size >= this.maxEntries) {\n const keyToDelete = this.cache.keys().next().value;\n this.cache.delete(keyToDelete);\n }\n this.cache.set(key, value);\n }\n\n /**\n * Get the MaxEntries of the cache.\n */\n public getMaxEntries(): number {\n return this.maxEntries;\n }\n\n /**\n * Set the MaxEntries of the cache. If the maxEntries is decreased, reduce\n * entries in the cache.\n */\n public setMaxEntries(maxEntries: number): void {\n if (maxEntries < 0) {\n throw new Error(\n `The maxEntries of LRU caches must be at least 0, but got ${\n maxEntries}.`);\n }\n\n if (this.maxEntries > maxEntries) {\n for (let i = 0; i < this.maxEntries - maxEntries; i++) {\n const keyToDelete = this.cache.keys().next().value;\n this.cache.delete(keyToDelete);\n }\n }\n\n this.maxEntries = maxEntries;\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(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(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: T|T[]): T[] {\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(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` 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(\n f: (...args: Array<{}>) => T, waitMs: number,\n nowFunc?: Function): (...args: Array<{}>) => T {\n let lastTime = nowFunc != null ? nowFunc() : util.now();\n let lastResult: T;\n const f2 = (...args: Array<{}>) => {\n const now = nowFunc != null ? nowFunc() : 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>;\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/**\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// 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;\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 = new Map();\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(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\nimport {backend} from '@tensorflow/tfjs-core';\nimport {DataFormat} from '../keras_format/common';\n\nlet _epsilon: number;\n\n/**\n * Returns the value of the fuzz factor used in numeric expressions.\n */\nexport function epsilon() {\n if (_epsilon == null) {\n _epsilon = backend().epsilon();\n }\n return _epsilon;\n}\n\n/**\n * Sets the value of the fuzz factor used in numeric expressions.\n * @param e New value of epsilon.\n */\nexport function setEpsilon(e: number) {\n _epsilon = e;\n}\n\n/**\n * Returns the default image data format convention.\n */\nexport function imageDataFormat(): DataFormat {\n return 'channelsLast';\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * 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(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, tidy, truncatedNormal, util, 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 override 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, this.seed);\n }\n\n override 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 override 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 override 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 override 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, this.seed);\n }\n }\n\n override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override className = 'LeCunUniform';\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 override 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 readonly ELEMENTS_WARN_SLOW = 2000;\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\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 (dtype !== 'int32' && dtype !== 'float32' && dtype !== undefined) {\n throw new TypeError(`Unsupported data type ${dtype}.`);\n }\n dtype = dtype as 'int32' | 'float32' | undefined;\n\n // flatten the input shape with the last dimension remaining its\n // original shape so it works for conv2d\n const numRows = util.sizeFromShape(shape.slice(0, -1));\n const numCols = shape[shape.length - 1];\n const numElements = numRows * numCols;\n if (numElements > this.ELEMENTS_WARN_SLOW) {\n console.warn(\n `Orthogonal initializer is being called on a matrix with more ` +\n `than ${this.ELEMENTS_WARN_SLOW} (${numElements}) elements: ` +\n `Slowness may result.`);\n }\n const flatShape =\n [Math.max(numCols, numRows), Math.min(numCols, numRows)];\n\n // Generate a random matrix\n const randNormalMat = K.randomNormal(flatShape, 0, 1, dtype, this.seed);\n\n // Compute QR factorization\n const qr = linalg.qr(randNormalMat, false);\n let qMat = qr[0];\n const rMat = qr[1];\n\n // Make Q uniform\n const diag = rMat.flatten().stridedSlice(\n [0], [Math.min(numCols, numRows) * Math.min(numCols, numRows)],\n [Math.min(numCols, numRows) + 1]);\n qMat = mul(qMat, diag.sign());\n if (numRows < numCols) {\n qMat = qMat.transpose();\n }\n\n return mul(scalar(this.gain), qMat.reshape(shape));\n });\n }\n\n override 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/* 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 '_' 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 * `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 const inputsList = 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 (inputsList.length !== inputSpec.length) {\n throw new ValueError(\n `Layer ${this.name} expects ${inputSpec.length} inputs, ` +\n `but it received ${inputsList.length} input tensors. ` +\n `Input received: ${inputs}`);\n }\n for (let inputIndex = 0; inputIndex < inputsList.length; inputIndex++) {\n const x = inputsList[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 can 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 const allAreSymbolic = checkAllSymbolic(inputs);\n const noneAreSymbolic = checkNoneSymbolic(inputs);\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, kwargs);\n\n // Apply masks to the output tensors if the layer supports it.\n if (this.supportsMasking) {\n // TODO(mattsoulanille): pass the input tensors' masks to computeMask\n this.setMaskMetadata(inputs, output);\n }\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, output, null, null, 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).slice(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, constraint?: Constraint,\n getInitializerFunc?: Function): 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 = getInitializerFunc != null ? getInitializerFunc() :\n 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 potentially 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 private setMaskMetadata(\n inputs: Tensor|Tensor[], outputs: Tensor|Tensor[],\n previousMask?: Tensor|Tensor[]): void {\n if (!this.supportsMasking) {\n return;\n }\n\n const outputMasks = this.computeMask(inputs, previousMask);\n const outputsList = generic_utils.toList(outputs);\n const outputMasksList = generic_utils.toList(outputMasks);\n\n if (outputsList.length !== outputMasksList.length) {\n throw new Error(\n `${this.name} outputs ${outputsList.length} tensors ` +\n `but ${outputsList.length} masks for those tensors`);\n }\n for (let i = 0; i < outputsList.length; i++) {\n outputsList[i].kerasMask = outputMasksList[i];\n }\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 standards 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 decreases 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\ntype MaybeSymbolic = SymbolicTensor|Tensor;\n\nfunction checkAllSymbolic(tensors: MaybeSymbolic|MaybeSymbolic[]):\n tensors is SymbolicTensor|SymbolicTensor[] {\n let allAreSymbolic = true;\n for (const tensor of generic_utils.toList(tensors)) {\n if (!(tensor instanceof SymbolicTensor)) {\n allAreSymbolic = false;\n break;\n }\n }\n return allAreSymbolic;\n}\n\nfunction checkNoneSymbolic(tensors: MaybeSymbolic|\n MaybeSymbolic[]): tensors is Tensor|Tensor[] {\n let noneAreSymbolic = true;\n for (const tensor of generic_utils.toList(tensors)) {\n if (tensor instanceof SymbolicTensor) {\n noneAreSymbolic = false;\n break;\n }\n }\n return noneAreSymbolic;\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 override 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 override dispose(): DisposeResult {\n // dispose() for InputLayer is overridden as no-op.\n return {refCountAfterDispose: this._refCount, numDisposedVariables: 0};\n }\n\n override 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/**\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 {LruCache} from '../utils/executor_utils';\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).\nexport const cachedSorted: LruCache =\n new LruCache();\n\n// Cache for recipient count maps for given execution targets (i.e., fetches).\nexport const cachedRecipientCounts: LruCache =\n new LruCache();\n\nexport function updateCacheMaxEntries(maxEntries: number) {\n if (cachedSorted != null) {\n cachedSorted.setMaxEntries(maxEntries);\n }\n if (cachedRecipientCounts != null) {\n cachedRecipientCounts.setMaxEntries(maxEntries);\n }\n}\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 : [fetches];\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().sort().join(',');\n let sorted: SymbolicTensor[] = cachedSorted.get(fetchAndFeedKey);\n let recipientCounts: {[fetchName: string]: number};\n if (sorted == 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.put(fetchAndFeedKey, sorted);\n cachedRecipientCounts.put(fetchAndFeedKey, recipientCounts);\n }\n recipientCounts = {};\n if (!training) {\n Object.assign(recipientCounts, cachedRecipientCounts.get(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;\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();\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();\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();\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();\n }\n recipientMap[input.name].add(top.name);\n\n if (visited.has(input.name)) {\n continue; // Avoid repeated visits to the same SymbolicTensor.\n }\n stack.push(input);\n }\n }\n }\n return {sorted, recipientMap};\n}\n\n/**\n * Get the symbolic output tensors of the node to which a given fetch belongs.\n * @param fetch The fetched symbolic tensor.\n * @returns The Array of symbolic tensors output by the node to which `fetch`\n * belongs.\n */\nfunction getNodeOutputs(fetch: SymbolicTensor): SymbolicTensor|\n SymbolicTensor[] {\n let layerOutputs: SymbolicTensor|SymbolicTensor[];\n if (fetch.sourceLayer.inboundNodes.length === 1) {\n layerOutputs = fetch.sourceLayer.output;\n } else {\n let nodeIndex: number = null;\n for (let i = 0; i < fetch.sourceLayer.inboundNodes.length; ++i) {\n for (const outputTensor of fetch.sourceLayer.inboundNodes[i]\n .outputTensors) {\n if (outputTensor.id === fetch.id) {\n nodeIndex = i;\n break;\n }\n }\n }\n layerOutputs = fetch.sourceLayer.getOutputAt(nodeIndex);\n }\n return layerOutputs;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/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 override 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 override 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 override 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 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nimport {updateCacheMaxEntries} from './engine/executor';\n\nexport const ENV = env();\n\n/** The max number of entries for the caches of layers' topological sort. */\nENV.registerFlag(\n 'TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES', () => 100, updateCacheMaxEntries);\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n// tslint:disable-next-line:max-line-length\nimport {Constraint, MaxNorm, MaxNormArgs, MinMaxNorm, MinMaxNormArgs, NonNeg, UnitNorm, UnitNormArgs} from './constraints';\n\n/**\n * MaxNorm weight constraint.\n *\n * Constrains the weights incident to each hidden unit\n * to have a norm less than or equal to a desired value.\n *\n * References\n * - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting\n * Srivastava, Hinton, et al.\n * 2014](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)\n *\n * @doc {heading: 'Constraints',namespace: 'constraints'}\n */\nexport function maxNorm(args: MaxNormArgs): Constraint {\n return new MaxNorm(args);\n}\n\n/**\n * Constrains the weights incident to each hidden unit to have unit norm.\n *\n * @doc {heading: 'Constraints', namespace: 'constraints'}\n */\nexport function unitNorm(args: UnitNormArgs): Constraint {\n return new UnitNorm(args);\n}\n\n/**\n * Constrains the weight to be non-negative.\n *\n * @doc {heading: 'Constraints', namespace: 'constraints'}\n */\nexport function nonNeg(): Constraint {\n return new NonNeg();\n}\n\n/** @doc {heading: 'Constraints', namespace: 'constraints'} */\nexport function minMaxNorm(config: MinMaxNormArgs): Constraint {\n return new MinMaxNorm(config);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n// tslint:disable-next-line:max-line-length\nimport {Constant, ConstantArgs, GlorotNormal, GlorotUniform, HeNormal, HeUniform, Identity, IdentityArgs, Initializer, LeCunNormal, LeCunUniform, Ones, Orthogonal, OrthogonalArgs, RandomNormal, RandomNormalArgs, RandomUniform, RandomUniformArgs, SeedOnlyInitializerArgs, TruncatedNormal, TruncatedNormalArgs, VarianceScaling, VarianceScalingArgs, Zeros} from './initializers';\n\n/**\n * Initializer that generates tensors initialized to 0.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function zeros(): Zeros {\n return new Zeros();\n}\n\n/**\n * Initializer that generates tensors initialized to 1.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function ones(): Initializer {\n return new Ones();\n}\n\n/**\n * Initializer that generates values initialized to some constant.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function constant(args: ConstantArgs): Initializer {\n return new Constant(args);\n}\n\n/**\n * Initializer that generates random values initialized to a uniform\n * distribution.\n *\n * Values will be distributed uniformly between the configured minval and\n * maxval.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function randomUniform(args: RandomUniformArgs): Initializer {\n return new RandomUniform(args);\n}\n\n/**\n * Initializer that generates random values initialized to a normal\n * distribution.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function randomNormal(args: RandomNormalArgs): Initializer {\n return new RandomNormal(args);\n}\n\n/**\n * Initializer that generates random values initialized to a truncated normal\n * distribution.\n *\n * These values are similar to values from a `RandomNormal` except that values\n * more than two standard deviations from the mean are discarded and re-drawn.\n * This is the recommended initializer for neural network weights and filters.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function truncatedNormal(args: TruncatedNormalArgs): Initializer {\n return new TruncatedNormal(args);\n}\n\n/**\n * Initializer that generates the identity matrix.\n * Only use for square 2D matrices.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function identity(args: IdentityArgs): Initializer {\n return new Identity(args);\n}\n\n/**\n * Initializer capable of adapting its scale to the shape of weights.\n * With distribution=NORMAL, samples are drawn from a truncated normal\n * distribution centered on zero, with `stddev = sqrt(scale / n)` where n is:\n * - number of input units in the weight tensor, if mode = FAN_IN.\n * - number of output units, if mode = FAN_OUT.\n * - average of the numbers of input and output units, if mode = FAN_AVG.\n * With distribution=UNIFORM,\n * samples are drawn from a uniform distribution\n * within [-limit, limit], with `limit = sqrt(3 * scale / n)`.\n *\n * @doc {heading: 'Initializers',namespace: 'initializers'}\n */\nexport function varianceScaling(config: VarianceScalingArgs): Initializer {\n return new VarianceScaling(config);\n}\n\n/**\n * Glorot uniform initializer, also called Xavier uniform initializer.\n * It draws samples from a uniform distribution within [-limit, limit]\n * where `limit` is `sqrt(6 / (fan_in + fan_out))`\n * where `fan_in` is the number of input units in the weight tensor\n * and `fan_out` is the number of output units in the weight tensor\n *\n * Reference:\n * Glorot & Bengio, AISTATS 2010\n * http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function glorotUniform(args: SeedOnlyInitializerArgs): Initializer {\n return new GlorotUniform(args);\n}\n\n/**\n * Glorot normal initializer, also called Xavier normal initializer.\n * It draws samples from a truncated normal distribution centered on 0\n * with `stddev = sqrt(2 / (fan_in + fan_out))`\n * where `fan_in` is the number of input units in the weight tensor\n * and `fan_out` is the number of output units in the weight tensor.\n *\n * Reference:\n * Glorot & Bengio, AISTATS 2010\n * http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function glorotNormal(args: SeedOnlyInitializerArgs): Initializer {\n return new GlorotNormal(args);\n}\n\n/**\n * He normal initializer.\n *\n * It draws samples from a truncated normal distribution centered on 0\n * with `stddev = sqrt(2 / fanIn)`\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * Reference:\n * He et al., http://arxiv.org/abs/1502.01852\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function heNormal(args: SeedOnlyInitializerArgs): Initializer {\n return new HeNormal(args);\n}\n\n/**\n * He uniform initializer.\n *\n * It draws samples from a uniform distribution within [-limit, limit]\n * where `limit` is `sqrt(6 / fan_in)`\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * Reference:\n * He et al., http://arxiv.org/abs/1502.01852\n *\n * @doc {heading: 'Initializers',namespace: 'initializers'}\n */\nexport function heUniform(args: SeedOnlyInitializerArgs): Initializer {\n return new HeUniform(args);\n}\n\n/**\n * LeCun normal initializer.\n *\n * It draws samples from a truncated normal distribution centered on 0\n * with `stddev = sqrt(1 / fanIn)`\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * References:\n * [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\n * [Efficient Backprop](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function leCunNormal(args: SeedOnlyInitializerArgs): Initializer {\n return new LeCunNormal(args);\n}\n\n/**\n * LeCun uniform initializer.\n *\n * It draws samples from a uniform distribution in the interval\n * `[-limit, limit]` with `limit = sqrt(3 / fanIn)`,\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function leCunUniform(args: SeedOnlyInitializerArgs): Initializer {\n return new LeCunUniform(args);\n}\n\n/**\n * Initializer that generates a random orthogonal matrix.\n *\n * Reference:\n * [Saxe et al., http://arxiv.org/abs/1312.6120](http://arxiv.org/abs/1312.6120)\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function orthogonal(args: OrthogonalArgs): Initializer {\n return new Orthogonal(args);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\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> = [];\n const keys: string[] = [];\n const scalarsToDispose: Scalar[] = [];\n for (const key in logs) {\n const value = logs[key];\n if (typeof value !== 'number') {\n const valueScalar = value;\n promises.push(valueScalar.data());\n keys.push(key);\n scalarsToDispose.push(valueScalar);\n }\n }\n if (promises.length > 0) {\n const values = await Promise.all(promises);\n for (let i = 0; i < values.length; ++i) {\n logs[keys[i]] = values[i][0];\n }\n // Dispose the original scalar tensors.\n dispose(scalarsToDispose);\n }\n}\n\n/**\n * Dispose all Tensors in an UnresolvedLogs object.\n *\n * @param logs An `UnresolvedLogs` object potentially containing `tf.Tensor`s in\n * places where the values can be `tf.Tensor` or `number`.\n */\nexport function disposeTensorsInLogs(logs: UnresolvedLogs) {\n if (logs == null) {\n return;\n }\n for (const key in logs) {\n const value = logs[key];\n if (typeof value !== 'number') {\n value.dispose();\n }\n }\n}\n\n/**\n * Logs in which values can only be numbers.\n *\n * Used when calling client-provided custom callbacks.\n */\nexport type Logs = {\n [key: string]: number;\n};\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/callbacks.py */\n\nimport {add, div, keep, mul, nextFrame, Scalar, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {Container} from './engine/container';\nimport {ValueError} from './errors';\nimport {Logs, resolveScalarsInLogs, UnresolvedLogs} from './logs';\nimport * as generic_utils from './utils/generic_utils';\n\n/** Verbosity logging level when fitting a model. */\nexport enum ModelLoggingVerbosity {\n SILENT = 0,\n VERBOSE = 1\n}\n\n/** How often to yield to the main thread when training (in ms). */\nexport const DEFAULT_YIELD_EVERY_MS = 125;\n\nexport type Params = {\n [key: string]: number|string|boolean|number[]|string[]|boolean[];\n};\n\nexport type YieldEveryOptions = 'auto'|'batch'|'epoch'|'never'|number;\n\n/**\n * Abstract base class used to build new callbacks.\n *\n * The `logs` dictionary that callback methods take as argument will contain\n * keys for quantities relevant to the current batch or epoch.\n *\n * Currently, the `.fit()` method of the `Sequential` model class\n * will include the following quantities in the `logs` that\n * it passes to its callbacks:\n *\n * onEpochEnd: Logs include `acc` and `loss`, and optionally include `valLoss`\n * (if validation is enabled in `fit`), and `valAcc` (if validation and\n * accuracy monitoring are enabled).\n * onBatchBegin: Logs include `size`, the number of samples in the current\n * batch.\n * onBatchEnd: Logs include `loss`, and optionally `acc` (if accuracy monitoring\n * is enabled).\n */\nexport abstract class BaseCallback {\n // TODO(michaelterry): This type is a best guess.\n validationData: Tensor|Tensor[] = null;\n /**\n * Training parameters (eg. verbosity, batch size, number of epochs...).\n */\n params: Params;\n\n setParams(params: Params): void {\n this.params = params;\n }\n\n async onEpochBegin(epoch: number, logs?: UnresolvedLogs) {}\n\n async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {}\n\n async onBatchBegin(batch: number, logs?: UnresolvedLogs) {}\n\n async onBatchEnd(batch: number, logs?: UnresolvedLogs) {}\n\n async onTrainBegin(logs?: UnresolvedLogs) {}\n\n async onTrainEnd(logs?: UnresolvedLogs) {}\n\n // LayersModel needs to call Callback.setModel(), but cannot actually depend\n // on Callback because that creates a cyclic dependency. Providing this no-op\n // method on BaseCallback breaks the cycle: this way LayersModel can depend on\n // BaseCallback but not on Callback. The argument is typed as `Container`\n // (the superclass of LayersModel) to avoid recapitulating the cycle. Callback\n // overrides this method and enforces that the argument is really a\n // LayersModel.\n setModel(model: Container): void {\n // Do nothing. Use Callback instead of BaseCallback to track the model.\n }\n}\n\n/**\n * Container abstracting a list of callbacks.\n */\nexport class CallbackList {\n callbacks: BaseCallback[];\n queueLength: number;\n\n // TODO(cais): When the need arises, uncomment the following lines and\n // implement the queue for time values.\n // private deltaTBatch: number;\n // private deltaTsBatchBegin: Array;\n // private deltaTsBatchEnd: Array;\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 override async onEpochBegin(epoch: number) {\n this.seen = 0;\n this.totals = {};\n }\n\n override 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 override 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};\n\n override async onTrainBegin(logs?: UnresolvedLogs) {\n this.epoch = [];\n this.history = {};\n }\n\n override 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> = [];\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;\n onTrainEnd?: (logs?: Logs) => void | Promise;\n onEpochBegin?: (epoch: number, logs?: Logs) => void | Promise;\n onEpochEnd?: (epoch: number, logs?: Logs) => void | Promise;\n onBatchBegin?: (batch: number, logs?: Logs) => void | Promise;\n onBatchEnd?: (batch: number, logs?: Logs) => void | Promise;\n onYield?: (epoch: number, batch: number, logs: Logs) => void | Promise;\n // Used for test DI mocking.\n nowFunc?: Function;\n nextFrameFunc?: Function;\n}\n\n/**\n * Custom callback for training.\n */\nexport class CustomCallback extends BaseCallback {\n protected readonly trainBegin: (logs?: Logs) => void | Promise;\n protected readonly trainEnd: (logs?: Logs) => void | Promise;\n protected readonly epochBegin:\n (epoch: number, logs?: Logs) => void | Promise;\n protected readonly epochEnd:\n (epoch: number, logs?: Logs) => void | Promise;\n protected readonly batchBegin:\n (batch: number, logs?: Logs) => void | Promise;\n protected readonly batchEnd:\n (batch: number, logs?: Logs) => void | Promise;\n protected readonly yield:\n (epoch: number, batch: number, logs: Logs) => void | Promise;\n\n private yieldEvery: YieldEveryOptions;\n private currentEpoch = 0;\n public nowFunc: Function;\n public nextFrameFunc: Function;\n\n constructor(args: CustomCallbackArgs, yieldEvery?: YieldEveryOptions) {\n super();\n this.nowFunc = args.nowFunc;\n this.nextFrameFunc = args.nextFrameFunc || nextFrame;\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, this.nowFunc);\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> = [];\n if (this.yield != null) {\n await resolveScalarsInLogs(logs);\n ps.push(this.yield(epoch, batch, logs as Logs));\n }\n ps.push(this.nextFrameFunc());\n await Promise.all(ps);\n }\n\n override async onEpochBegin(epoch: number, logs?: UnresolvedLogs):\n Promise {\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 override async onEpochEnd(epoch: number, logs?: UnresolvedLogs):\n Promise {\n const ps: Array> = [];\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(this.nextFrameFunc());\n }\n await Promise.all(ps);\n }\n\n override async onBatchBegin(batch: number, logs?: UnresolvedLogs):\n Promise {\n if (this.batchBegin != null) {\n await resolveScalarsInLogs(logs);\n await this.batchBegin(batch, logs as Logs);\n }\n }\n\n override async onBatchEnd(batch: number, logs?: UnresolvedLogs):\n Promise {\n const ps: Array> = [];\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(this.nextFrameFunc());\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 override async onTrainBegin(logs?: UnresolvedLogs): Promise {\n if (this.trainBegin != null) {\n await resolveScalarsInLogs(logs);\n await this.trainBegin(logs as Logs);\n }\n }\n\n override async onTrainEnd(logs?: UnresolvedLogs): Promise {\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(\n callbacks) as CustomCallbackArgs[];\n return callbackConfigs.map(\n callbackConfig => new CustomCallback(callbackConfig, yieldEvery));\n}\n\nexport declare type BaseCallbackConstructor = {\n new (): BaseCallback\n};\n\n/**\n * A global registry for callback constructors to be used during\n * LayersModel.fit().\n */\nexport class CallbackConstructorRegistry {\n private static constructors:\n {[verbosityLevel: number]: BaseCallbackConstructor[]} = {};\n\n /**\n * Blocks public access to constructor.\n */\n private constructor() {}\n\n /**\n * Register a tf.LayersModel.fit() callback constructor.\n *\n * The registered callback constructor will be used to instantiate\n * callbacks for every tf.LayersModel.fit() call afterwards.\n *\n * @param verbosityLevel Level of verbosity at which the `callbackConstructor`\n * is to be reigstered.\n * @param callbackConstructor A no-arg constructor for `tf.Callback`.\n * @throws Error, if the same callbackConstructor has been registered before,\n * either at the same or a different `verbosityLevel`.\n */\n static registerCallbackConstructor(\n verbosityLevel: number, callbackConstructor: BaseCallbackConstructor) {\n util.assert(\n verbosityLevel >= 0 && Number.isInteger(verbosityLevel),\n () => `Verbosity level is expected to be an integer >= 0, ` +\n `but got ${verbosityLevel}`);\n CallbackConstructorRegistry.checkForDuplicate(callbackConstructor);\n if (CallbackConstructorRegistry.constructors[verbosityLevel] == null) {\n CallbackConstructorRegistry.constructors[verbosityLevel] = [];\n }\n CallbackConstructorRegistry.constructors[verbosityLevel].push(\n callbackConstructor);\n }\n\n private static checkForDuplicate(callbackConstructor:\n BaseCallbackConstructor) {\n for (const levelName in CallbackConstructorRegistry.constructors) {\n const constructors = CallbackConstructorRegistry.constructors[+levelName];\n constructors.forEach(ctor => {\n if (ctor === callbackConstructor) {\n throw new ValueError('Duplicate callback constructor.');\n }\n });\n }\n }\n\n /**\n * Clear all registered callback constructors.\n */\n protected static clear() {\n CallbackConstructorRegistry.constructors = {};\n }\n\n /**\n * Create callbacks using the registered callback constructors.\n *\n * Given `verbosityLevel`, all constructors registered at that level or above\n * will be called and the instantiated callbacks will be used.\n *\n * @param verbosityLevel: Level of verbosity.\n */\n static createCallbacks(verbosityLevel: number): BaseCallback[] {\n const constructors: BaseCallbackConstructor[] = [];\n for (const levelName in CallbackConstructorRegistry.constructors) {\n const level = +levelName;\n if (verbosityLevel >= level) {\n constructors.push(...CallbackConstructorRegistry.constructors[level]);\n }\n }\n return constructors.map(ctor => new ctor());\n }\n}\n\nexport function configureCallbacks(\n callbacks: BaseCallback[], verbose: ModelLoggingVerbosity, epochs: number,\n initialEpoch: number, numTrainSamples: number, stepsPerEpoch: number,\n batchSize: number, doValidation: boolean,\n callbackMetrics: string[]): {callbackList: CallbackList, history: History} {\n const history = new History();\n const actualCallbacks: BaseCallback[] = [\n new BaseLogger(), ...CallbackConstructorRegistry.createCallbacks(verbose)\n ];\n if (callbacks != null) {\n actualCallbacks.push(...callbacks);\n }\n actualCallbacks.push(history);\n const callbackList = new CallbackList(actualCallbacks);\n\n // TODO(cais): Figure out when this LayersModel instance can have a\n // dynamically\n // set property called 'callback_model' as in PyKeras.\n\n callbackList.setParams({\n epochs,\n initialEpoch,\n samples: numTrainSamples,\n steps: stepsPerEpoch,\n batchSize,\n verbose,\n doValidation,\n metrics: callbackMetrics,\n });\n return {callbackList, history};\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original Source layers/__init__.py */\nimport {serialization} from '@tensorflow/tfjs-core';\n\nimport {deserializeKerasObject} from '../utils/generic_utils';\n\n/**\n * Instantiate a layer from a config dictionary.\n * @param config dict of the form {class_name: str, config: dict}\n * @param customObjects dict mapping class names (or function names)\n * of custom (non-Keras) objects to class/functions\n * @param fastWeightInit Optional flag to use fast weight initialization\n * during deserialization. This is applicable to cases in which\n * the initialization will be immediately overwritten by loaded weight\n * values. Default: `false`.\n * @returns Layer instance (may be LayersModel, Sequential, Layer...)\n */\nexport function deserialize(\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict,\n fastWeightInit = false): serialization.Serializable {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'layer', fastWeightInit);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original Source: losses.py */\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {Tensor, Tensor1D, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {epsilon} from './backend/common';\nimport * as K from './backend/tfjs_backend';\nimport {ValueError} from './errors';\nimport {LossOrMetricFn} from './types';\n\n/**\n * Normalizes a tensor wrt the L2 norm alongside the specified axis.\n * @param x\n * @param axis Axis along which to perform normalization.\n */\nexport function l2Normalize(x: Tensor, axis?: number): Tensor {\n return tidy(() => {\n if (x.dtype !== 'float32') {\n x = tfc.cast(x, 'float32');\n }\n const squareSum = tfc.sum(K.square(x), axis, true);\n const epsilonTensor = tfc.fill(squareSum.shape, epsilon());\n const norm = tfc.sqrt(tfc.maximum(squareSum, epsilonTensor));\n return tfc.div(x, norm);\n });\n}\n\nexport function meanSquaredError(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => tfc.mean(K.square(tfc.sub(yPred, yTrue)), -1));\n}\n\nexport function meanAbsoluteError(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => tfc.mean(tfc.abs(tfc.sub(yPred, yTrue)), -1));\n}\n\nexport function meanAbsolutePercentageError(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const diff = tfc.sub(yTrue, yPred);\n const clippedTrue =\n tfc.clipByValue(tfc.abs(yTrue), epsilon(), Number.MAX_VALUE);\n const absResult = tfc.abs(tfc.div(diff, clippedTrue));\n return tfc.mul(100, tfc.mean(absResult, -1));\n });\n}\n\nexport function meanSquaredLogarithmicError(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const clippedPred = tfc.clipByValue(yPred, epsilon(), Number.MAX_VALUE);\n const firstLog = tfc.log(tfc.add(1, clippedPred));\n\n const clippedTrue = tfc.clipByValue(yTrue, epsilon(), Number.MAX_VALUE);\n const secondLog = tfc.log(tfc.add(1, clippedTrue));\n\n return tfc.mean(K.square(tfc.sub(firstLog, secondLog)), -1);\n });\n}\n\nexport function squaredHinge(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const maxResult = tfc.maximum(0, tfc.sub(1, tfc.mul(yTrue, yPred)));\n return tfc.mean(K.square(maxResult), -1);\n });\n}\n\nexport function hinge(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const maxResult = tfc.maximum(0, tfc.sub(1, tfc.mul(yTrue, yPred)));\n return tfc.mean(maxResult, -1);\n });\n}\n\nexport function categoricalHinge(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const pos = tfc.sum(tfc.mul(yTrue, yPred), -1);\n const neg = tfc.max(tfc.mul(tfc.sub(1, yTrue), yPred), -1);\n return tfc.maximum(0, tfc.add(1, tfc.sub(neg, pos)));\n });\n}\n\n/**\n * Logarithm of the hyperbolic cosine of the prediction error.\n *\n * `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and\n * to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly\n * like the mean squared error, but will not be so strongly affected by the\n * occasional wildly incorrect prediction.\n */\nexport function logcosh(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const log2 = Math.log(2);\n const predictionDiff = tfc.sub(yPred, yTrue);\n const logcoshResult = tfc.sub(\n tfc.add(predictionDiff, tfc.softplus(tfc.mul(-2, predictionDiff))),\n log2);\n return tfc.mean(logcoshResult, -1);\n });\n}\n\nexport function categoricalCrossentropy(\n target: Tensor, output: Tensor, fromLogits = false): Tensor {\n return tidy(() => {\n if (fromLogits) {\n output = tfc.softmax(output);\n } else {\n // scale preds so that the class probabilities of each sample sum to 1.\n const outputSum = tfc.sum(output, output.shape.length - 1, true);\n output = tfc.div(output, outputSum);\n }\n output = tfc.clipByValue(output, epsilon(), 1 - epsilon());\n return tfc.neg(tfc.sum(\n tfc.mul(tfc.cast(target, 'float32'), tfc.log(output)),\n output.shape.length - 1));\n });\n}\n\n/**\n * Categorical crossentropy with integer targets.\n *\n * @param target An integer tensor.\n * @param output A tensor resulting from a softmax (unless `fromLogits` is\n * `true`, in which case `output` is expected to be the logits).\n * @param fromLogits Boolean, whether `output` is the result of a softmax, or is\n * a tensor of logits.\n */\nexport function sparseCategoricalCrossentropy(\n target: Tensor, output: Tensor, fromLogits = false): Tensor {\n return tidy(() => {\n const flatTarget =\n tfc.cast(tfc.floor(K.flatten(target)), 'int32') as Tensor1D;\n output = tfc.clipByValue(output, epsilon(), 1 - epsilon());\n const outputShape = output.shape;\n const oneHotTarget = tfc.reshape(\n tfc.oneHot(flatTarget, outputShape[outputShape.length - 1]),\n outputShape);\n return categoricalCrossentropy(oneHotTarget, output, fromLogits);\n });\n}\n\n/**\n * From TensorFlow's implementation in nn_impl.py:\n *\n * For brevity, let `x = logits`, `z = labels`. The logistic loss is\n * z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n * = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n * = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n * = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n * = (1 - z) * x + log(1 + exp(-x))\n * = x - x * z + log(1 + exp(-x))\n * For x < 0, to avoid overflow in exp(-x), we reformulate the above\n * x - x * z + log(1 + exp(-x))\n * = log(exp(x)) - x * z + log(1 + exp(-x))\n * = - x * z + log(1 + exp(x))\n * Hence, to ensure stability and avoid overflow, the implementation uses this\n * equivalent formulation\n * max(x, 0) - x * z + log(1 + exp(-abs(x)))\n *\n * @param labels The labels.\n * @param logits The logits.\n */\nexport function sigmoidCrossEntropyWithLogits(\n labels: Tensor, logits: Tensor): Tensor {\n if (!util.arraysEqual(labels.shape, logits.shape)) {\n throw new ValueError(\n `logits and labels must have the same shape, but got shapes ` +\n `${JSON.stringify(labels.shape)} and ${JSON.stringify(logits.shape)}`);\n }\n return tidy(() => {\n // The logistic loss formula from above is\n // x - x * z + log(1 + exp(-x))\n // For x < 0, a more numerically stable formula is\n // -x * z + log(1 + exp(x))\n // Note that these two expressions can be combined into the following:\n // max(x, 0) - x * z + log(1 + exp(-abs(x)))\n const reluLogits = tfc.relu(logits);\n const negAbsLogits = tfc.neg(tfc.abs(logits));\n return tfc.add(\n tfc.sub(reluLogits, tfc.mul(logits, labels)),\n tfc.log1p(tfc.exp(negAbsLogits)));\n });\n}\n\nexport function binaryCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n let y: Tensor;\n y = tfc.clipByValue(yPred, epsilon(), 1 - epsilon());\n y = tfc.log(tfc.div(y, tfc.sub(1, y)));\n return tfc.mean(sigmoidCrossEntropyWithLogits(yTrue, y), -1);\n });\n}\n\nexport function kullbackLeiblerDivergence(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const clippedTrue = tfc.clipByValue(yTrue, epsilon(), 1);\n const clippedPred = tfc.clipByValue(yPred, epsilon(), 1);\n return tfc.sum(\n tfc.mul(yTrue, tfc.log(tfc.div(clippedTrue, clippedPred))), -1);\n });\n}\n\nexport function poisson(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const logPred = tfc.log(tfc.add(epsilon(), yPred));\n return tfc.mean(tfc.sub(yPred, tfc.mul(yTrue, logPred)), -1);\n });\n}\n\nexport function cosineProximity(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const trueNormalized = l2Normalize(yTrue, -1);\n const predNormalized = l2Normalize(yPred, -1);\n const trueXPred = tfc.mul(trueNormalized, predNormalized);\n return tfc.neg(tfc.sum(trueXPred, -1));\n });\n}\n\nexport const mse = meanSquaredError;\nexport const MSE = meanSquaredError;\nexport const mae = meanAbsoluteError;\nexport const MAE = meanAbsoluteError;\nexport const mape = meanAbsolutePercentageError;\nexport const MAPE = meanAbsolutePercentageError;\nexport const msle = meanSquaredLogarithmicError;\nexport const MSLE = meanSquaredLogarithmicError;\nexport const kld = kullbackLeiblerDivergence;\nexport const KLD = kullbackLeiblerDivergence;\nexport const cosine = cosineProximity;\n\n// TODO(michaelterry): Add deserialize() function.\n\nexport const lossesMap: {[functionName: string]: LossOrMetricFn} = {\n meanSquaredError,\n meanAbsoluteError,\n meanAbsolutePercentageError,\n meanSquaredLogarithmicError,\n squaredHinge,\n hinge,\n categoricalHinge,\n logcosh,\n categoricalCrossentropy,\n sparseCategoricalCrossentropy,\n binaryCrossentropy,\n kullbackLeiblerDivergence,\n poisson,\n cosineProximity\n};\n\n// Porting note: This diverges from the PyKeras implementation and may need to\n// change based on (de)serialization requirements.\nexport function get(identifierOrFn: string|LossOrMetricFn): LossOrMetricFn {\n if (typeof identifierOrFn === 'string') {\n if (identifierOrFn in lossesMap) {\n return lossesMap[identifierOrFn];\n }\n let errMsg = `Unknown loss ${identifierOrFn}`;\n if (identifierOrFn.toLowerCase().includes('softmaxcrossentropy')) {\n errMsg = `Unknown loss ${identifierOrFn}. ` +\n 'Use \"categoricalCrossentropy\" as the string name for ' +\n 'tf.losses.softmaxCrossEntropy';\n }\n throw new ValueError(errMsg);\n } else {\n return identifierOrFn;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Built-in metrics.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {Tensor, tidy} from '@tensorflow/tfjs-core';\n\nimport * as K from './backend/tfjs_backend';\nimport {NotImplementedError, ValueError} from './errors';\nimport {categoricalCrossentropy as categoricalCrossentropyLoss, cosineProximity, meanAbsoluteError, meanAbsolutePercentageError, meanSquaredError, sparseCategoricalCrossentropy as sparseCategoricalCrossentropyLoss} from './losses';\nimport {binaryCrossentropy as lossBinaryCrossentropy} from './losses';\nimport {lossesMap} from './losses';\nimport {LossOrMetricFn} from './types';\nimport * as util from './utils/generic_utils';\n\nexport function binaryAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const threshold = tfc.mul(.5, tfc.onesLike(yPred));\n const yPredThresholded = K.cast(tfc.greater(yPred, threshold), yTrue.dtype);\n return tfc.mean(tfc.equal(yTrue, yPredThresholded), -1);\n });\n}\n\nexport function categoricalAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(\n () => K.cast(\n tfc.equal(tfc.argMax(yTrue, -1), tfc.argMax(yPred, -1)), 'float32'));\n}\n\nfunction truePositives(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n return tfc.cast(\n tfc.sum(tfc.logicalAnd(tfc.equal(yTrue, 1), tfc.equal(yPred, 1))),\n 'float32');\n });\n}\n\nfunction falseNegatives(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n return tfc.cast(\n tfc.sum(tfc.logicalAnd(tfc.equal(yTrue, 1), tfc.equal(yPred, 0))),\n 'float32');\n });\n}\n\nfunction falsePositives(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n return tfc.cast(\n tfc.sum(tfc.logicalAnd(tfc.equal(yTrue, 0), tfc.equal(yPred, 1))),\n 'float32');\n });\n}\n\nexport function precision(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const tp = truePositives(yTrue, yPred);\n const fp = falsePositives(yTrue, yPred);\n\n const denominator = tfc.add(tp, fp);\n\n return tfc.cast(\n tfc.where(tfc.greater(denominator, 0), tfc.div(tp, denominator), 0),\n 'float32');\n });\n}\n\nexport function recall(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const tp = truePositives(yTrue, yPred);\n const fn = falseNegatives(yTrue, yPred);\n\n const denominator = tfc.add(tp, fn);\n\n return tfc.cast(\n tfc.where(tfc.greater(denominator, 0), tfc.div(tp, denominator), 0),\n 'float32');\n });\n}\n\nexport function binaryCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return lossBinaryCrossentropy(yTrue, yPred);\n}\n\nexport function sparseCategoricalAccuracy(\n yTrue: Tensor, yPred: Tensor): Tensor {\n if (yTrue.rank === yPred.rank) {\n yTrue = tfc.squeeze(yTrue, [yTrue.rank - 1]);\n }\n yPred = tfc.argMax(yPred, -1);\n if (yPred.dtype !== yTrue.dtype) {\n yPred = tfc.cast(yPred, yTrue.dtype);\n }\n return tfc.cast(tfc.equal(yTrue, yPred), 'float32');\n}\n\nexport function topKCategoricalAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n throw new NotImplementedError();\n}\n\nexport function sparseTopKCategoricalAccuracy(\n yTrue: Tensor, yPred: Tensor): Tensor {\n throw new NotImplementedError();\n}\n\n// Aliases.\nexport const mse = meanSquaredError;\nexport const MSE = meanSquaredError;\nexport const mae = meanAbsoluteError;\nexport const MAE = meanAbsoluteError;\nexport const mape = meanAbsolutePercentageError;\nexport const MAPE = meanAbsolutePercentageError;\nexport const categoricalCrossentropy = categoricalCrossentropyLoss;\nexport const cosine = cosineProximity;\nexport const sparseCategoricalCrossentropy = sparseCategoricalCrossentropyLoss;\n\n// TODO(cais, nielsene): Add serialize().\n\nexport const metricsMap: {[functionName: string]: LossOrMetricFn} = {\n binaryAccuracy,\n categoricalAccuracy,\n precision,\n categoricalCrossentropy,\n sparseCategoricalCrossentropy,\n mse,\n MSE,\n mae,\n MAE,\n mape,\n MAPE,\n cosine\n};\n\nexport function get(identifier: string|LossOrMetricFn): LossOrMetricFn {\n if (typeof identifier === 'string' && identifier in metricsMap) {\n return metricsMap[identifier];\n } else if (typeof identifier !== 'string' && identifier != null) {\n return identifier;\n } else {\n throw new ValueError(`Unknown metric ${identifier}`);\n }\n}\n\n/**\n * Get the shortcut function name.\n *\n * If the fn name is a string,\n * directly return the string name.\n * If the function is included in metricsMap or lossesMap,\n * return key of the map.\n * - If the function relative to multiple keys,\n * return the first found key as the function name.\n * - If the function exists in both lossesMap and metricsMap,\n * search lossesMap first.\n * If the function is not included in metricsMap or lossesMap,\n * return the function name.\n *\n * @param fn loss function, metric function, or short cut name.\n * @returns Loss or Metric name in string.\n */\nexport function getLossOrMetricName(fn: string|LossOrMetricFn): string {\n util.assert(fn !== null, `Unknown LossOrMetricFn ${fn}`);\n if (typeof fn === 'string') {\n return fn;\n } else {\n let fnName;\n for (const key of Object.keys(lossesMap)) {\n if (lossesMap[key] === fn) {\n fnName = key;\n break;\n }\n }\n if (fnName !== undefined) {\n return fnName;\n }\n for (const key of Object.keys(metricsMap)) {\n if (metricsMap[key] === fn) {\n fnName = key;\n break;\n }\n }\n if (fnName !== undefined) {\n return fnName;\n }\n return (fn as Function).name;\n }\n}\n","/**\n * @license\n * Copyright 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)', 'Input Shape', 'Output shape', 'Param #'];\n if (sequentialLike) {\n lineLength = lineLength || 90;\n positions = positions || [0.32, 0.61, 0.89, 1];\n } else {\n lineLength = lineLength || 115;\n positions = positions || [0.24, 0.48, 0.70, 0.80, 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 let inputShape: string;\n\n try {\n inputShape = (layer.inboundNodes.map(\n x => JSON.stringify(x.inputShapes)\n )).join(',');\n } catch (err) {\n inputShape = 'multiple';\n }\n\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})`, inputShape,\n 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 let inputShape: string;\n\n try {\n inputShape = (layer.inboundNodes.map(\n x => JSON.stringify(x.inputShapes)\n )).join(',');\n } catch (err) {\n inputShape = 'multiple';\n }\n\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})`, inputShape,\n 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(\n key: string, index: number, value: T): boolean {\n return (key === 'inboundNodes' || key === 'outputLayers' ||\n key === 'inputLayers') &&\n index === 0 && typeof value === 'string';\n}\n\n/**\n * Convert a Pythonic config object to TypeScript config object.\n * @param pythonicConfig The config object to convert.\n * @param key Optional key name of the object being converted.\n * @returns Result of the conversion.\n */\nexport function convertPythonicToTs(\n pythonicConfig: PyJsonValue, key?: string): serialization.ConfigDictValue {\n if (pythonicConfig === null) {\n return null;\n } else if (typeof pythonicConfig === 'string') {\n return generic_utils.toCamelCase(pythonicConfig);\n } else if (\n (typeof pythonicConfig === 'number') ||\n (typeof pythonicConfig === 'boolean')) {\n return pythonicConfig;\n } else if (pythonicConfig instanceof Array) {\n const tsArray = [];\n const arrayLength = pythonicConfig.length;\n for (let i = 0; i < arrayLength; ++i) {\n const item = pythonicConfig[i];\n if (isArrayItemInputOrOutputName(key, i, item)) {\n tsArray.push(item);\n } else {\n tsArray.push(convertPythonicToTs(item, key));\n }\n }\n return tsArray;\n } else {\n const tsDict: serialization.ConfigDict = {};\n for (const pythonicKey of Object.keys(pythonicConfig)) {\n const pythonicValue = pythonicConfig[pythonicKey];\n if (pythonicKey === 'name' && typeof pythonicValue === 'string') {\n // Special case the 'name' key with a string value. Name values, such as\n // the names of LayersModel and Layer instances, should not undergo the\n // camel-case conversion.\n tsDict[pythonicKey] = pythonicValue;\n } else {\n const tsKey = generic_utils.toCamelCase(pythonicKey);\n tsDict[tsKey] = convertPythonicToTs(pythonicValue, tsKey);\n }\n }\n return tsDict;\n }\n}\n\n/**\n * Convert a TypeScript config object to Python config object.\n * @param tsConfig The config object to convert.\n * @param key Optional key name of the object being converted.\n * @returns Result of the conversion.\n */\nexport function convertTsToPythonic(\n tsConfig: serialization.ConfigDictValue, key?: string): PyJsonValue {\n if (tsConfig === null || tsConfig === undefined) {\n return null;\n } else if (typeof tsConfig === 'string') {\n return generic_utils.toSnakeCase(tsConfig);\n } else if (\n (typeof tsConfig === 'number') || (typeof tsConfig === 'boolean')) {\n return tsConfig;\n } else if (tsConfig instanceof Array) {\n const pyArray = [];\n const arrayLength = tsConfig.length;\n for (let i = 0; i < arrayLength; ++i) {\n const item = tsConfig[i];\n if (isArrayItemInputOrOutputName(key, i, item)) {\n pyArray.push(item);\n } else {\n pyArray.push(convertTsToPythonic(item, key));\n }\n }\n return pyArray;\n } else {\n const pyDict: serialization.ConfigDict = {};\n for (const tsKey of Object.keys(tsConfig)) {\n const tsValue = tsConfig[tsKey];\n const pyKey = generic_utils.toSnakeCase(tsKey);\n if ((tsKey === 'name' || tsKey === 'className') &&\n typeof tsValue === 'string') {\n // Special case the 'name' key with a string value. Name values, such as\n // the names of LayersModel and Layer instances, should not undergo the\n // snake-case conversion.\n pyDict[pyKey] = tsValue;\n } else {\n pyDict[pyKey] = convertTsToPythonic(tsValue, tsKey);\n }\n }\n return pyDict;\n }\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.0';\nexport {version};\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* 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// get weights key from tensor map in order to check if it is from keras v3.\n// e.g. dense/0\nconst isKerasSavedModelFormat = (weights: NamedTensorMap): boolean => {\n const keys = Object.keys(weights);\n if (keys.length === 0) {\n return false;\n }\n const key = keys[0].split('/');\n return !isNaN(parseInt(key[key.length - 1], 10));\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();\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 override 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 override 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 override get trainable() {\n return this.trainable_;\n }\n\n override 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 override 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 override 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 override 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 const modelIsKerasSavedModelFormat = isKerasSavedModelFormat(weights);\n if (modelIsKerasSavedModelFormat) {\n this.parseWeights(weights);\n }\n // Check if weights from keras v3.\n for (const layer of this.layers) {\n for (const [index, weight] of layer.weights.entries()) {\n // Parse the name to layerName/index.\n // e.g. dense/0, dense/1, dense_1/0, dense_1/1\n const parsedName = modelIsKerasSavedModelFormat ?\n `${weight.name.split('/').slice(0, -1).join('/') + '/'}${index}` :\n weight.originalName;\n if (nameToWeight[parsedName] != null) {\n throw new ValueError(`Duplicate weight name: ${parsedName}`);\n }\n nameToWeight[parsedName] = 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 protected parseWeights(weights: NamedTensorMap) {\n for (const key in Object.keys(weights)) {\n const listParts = key.split('/');\n const list = ['vars', 'layer_checkpoint_dependencies'];\n // For keras v3, the weights name are saved based on the folder structure.\n // e.g. _backbone/_layer_checkpoint_dependencies/transformer/_self../\n // _output_dense/vars/0\n // Therefore we discard the `vars` and `layer_checkpoint_depencies` within\n // the saved name and only keeps the layer name and weights.\n // This can help to mapping the actual name of the layers and load each\n // weight accordingly.\n const newKey = listParts\n .map(str => {\n if (str.startsWith('_')) {\n return str.slice(1);\n }\n return str;\n })\n .filter(str => !list.includes(str))\n .join('/');\n if (newKey !== key) {\n weights[newKey] = weights[key];\n delete weights[key];\n }\n }\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 override 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 override 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 override 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): Layer;\n getLayer(index: number): Layer;\n getLayer(name: string, index: number): Layer;\n getLayer(nameOrIndex?: string|number, index?: number): Layer {\n if (index != null) {\n return this.findLayer(index);\n } else {\n if (nameOrIndex == null) {\n throw new ValueError('Provide either a layer name or layer index');\n }\n if (typeof nameOrIndex === 'number') {\n return this.findLayer(nameOrIndex);\n }\n }\n\n for (const layer of this.layers) {\n if (layer.name === nameOrIndex) {\n return layer;\n }\n }\n throw new ValueError(`No such layer: ${nameOrIndex}`);\n }\n\n findLayer(index: number): Layer {\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 }\n\n /**\n * Retrieves the Container's current loss values.\n *\n * Used for regularizers during training.\n */\n override 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 override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 override 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 override resetStates() {\n tidy(() => {\n this.layers.forEach(layer => {\n // tslint:disable:no-any\n if (layer.stateful) {\n layer.resetStates();\n }\n // tslint:enable:no-any\n });\n });\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {argMax, clone, dispose, mul, reshape, Tensor, Tensor1D, tensor1d, tidy} from '@tensorflow/tfjs-core';\n\n/**\n * For multi-class classification problems, this object is designed to store a\n * mapping from class index to the \"weight\" of the class, where higher weighted\n * classes have larger impact on loss, accuracy, and other metrics.\n *\n * This is useful for cases in which you want the model to \"pay more attention\"\n * to examples from an under-represented class, e.g., in unbalanced datasets.\n */\nexport type ClassWeight = {\n [classIndex: number]: number\n};\n\n/**\n * Class weighting for a model with multiple outputs.\n *\n * This object maps each output name to a class-weighting object.\n */\nexport type ClassWeightMap = {\n [outputName: string]: ClassWeight\n};\n\nfunction standardizeSampleOrClassWeights(\n xWeight: ClassWeight|ClassWeight[]|ClassWeightMap, outputNames: string[],\n weightType: 'sampleWeight'|'classWeight'): ClassWeight[] {\n const numOutputs = outputNames.length;\n if (xWeight == null || (Array.isArray(xWeight) && xWeight.length === 0)) {\n return outputNames.map(name => null);\n }\n if (numOutputs === 1) {\n if (Array.isArray(xWeight) && xWeight.length === 1) {\n return xWeight;\n } else if (typeof xWeight === 'object' && outputNames[0] in xWeight) {\n return [(xWeight as ClassWeightMap)[outputNames[0]]];\n } else {\n return [xWeight as ClassWeight];\n }\n }\n if (Array.isArray(xWeight)) {\n if (xWeight.length !== numOutputs) {\n throw new Error(\n `Provided ${weightType} is an array of ${xWeight.length} ` +\n `element(s), but the model has ${numOutputs} outputs. ` +\n `Make sure a set of weights is provided for each model output.`);\n }\n return xWeight;\n } else if (\n typeof xWeight === 'object' && Object.keys(xWeight).length > 0 &&\n typeof (xWeight as ClassWeightMap)[Object.keys(xWeight)[0]] ===\n 'object') {\n const output: ClassWeight[] = [];\n outputNames.forEach(outputName => {\n if (outputName in xWeight) {\n output.push((xWeight as ClassWeightMap)[outputName]);\n } else {\n output.push(null);\n }\n });\n return output;\n } else {\n throw new Error(\n `The model has multiple (${numOutputs}) outputs, ` +\n `so ${weightType} must be either an array with ` +\n `${numOutputs} elements or an object with ${outputNames} keys. ` +\n `Provided ${weightType} not understood: ${JSON.stringify(xWeight)}`);\n }\n}\n\n/**\n * Standardize class weighting objects.\n *\n * This function takes a single class-weighting object, an array of them,\n * or a map from output name to class-weighting object. It compares it to the\n * output name(s) of the model, base on which it outputs an array of\n * class-weighting objects of which the length matches the number of outputs.\n *\n * @param classWeight Input class-weighting object(s).\n * @param outputNames All output name(s) of the model.\n * @return An array of class-weighting objects. The length of the array matches\n * the model's number of outputs.\n */\nexport function standardizeClassWeights(\n classWeight: ClassWeight|ClassWeight[]|ClassWeightMap,\n outputNames: string[]): ClassWeight[] {\n return standardizeSampleOrClassWeights(\n classWeight, outputNames, 'classWeight');\n}\n\nexport function standardizeSampleWeights(\n classWeight: ClassWeight|ClassWeight[]|ClassWeightMap,\n outputNames: string[]): ClassWeight[] {\n return standardizeSampleOrClassWeights(\n classWeight, outputNames, 'sampleWeight');\n}\n\n/**\n * Standardize by-sample and/or by-class weights for training.\n *\n * Note that this function operates on one model output at a time. For a model\n * with multiple outputs, you must call this function multiple times.\n *\n * @param y The target tensor that the by-sample and/or by-class weight is for.\n * The values of y are assumed to encode the classes, either directly\n * as an integer index, or as one-hot encoding.\n * @param sampleWeight By-sample weights.\n * @param classWeight By-class weights: an object mapping class indices\n * (integers) to a weight (float) to apply to the model's loss for the\n * samples from this class during training. This can be useful to tell the\n * model to \"pay more attention\" to samples from an under-represented class.\n * @param sampleWeightMode The mode for the sample weights.\n * @return A Promise of weight tensor, of which the size of the first dimension\n * matches that of `y`.\n */\nexport async function standardizeWeights(\n y: Tensor, sampleWeight?: Tensor, classWeight?: ClassWeight,\n sampleWeightMode?: 'temporal'): Promise {\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 {\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;\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 an 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(\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(\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,\n args: ModelFitDatasetArgs): Promise {\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(\n dataset: Dataset, args: ModelFitDatasetArgs): 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(\n dataset:\n [\n TensorOrArrayOrMap, TensorOrArrayOrMap\n ]|[TensorOrArrayOrMap, TensorOrArrayOrMap, TensorOrArrayOrMap]|\n Dataset): boolean {\n return (typeof (dataset as Dataset).iterator === 'function');\n}\n\n// Check if provided object is a LazyIterator object by checking it's .next\n// element.\nfunction isLazyIteratorObject(iterator: Dataset|\n LazyIterator): boolean {\n return (typeof (iterator as LazyIterator).next === 'function');\n}\n\nexport async function evaluateDataset(\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|LazyIterator,\n args: ModelEvaluateDatasetArgs): Promise {\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:\n await (dataset as Dataset).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 {Tensor, Tensor1D} from '@tensorflow/tfjs-core';\nimport {expandDims, gather, sliceAlongFirstAxis} from '../backend/tfjs_backend';\nimport {BaseCallback, CustomCallbackArgs, ModelLoggingVerbosity, YieldEveryOptions} from '../base_callbacks';\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 | 2;\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 an 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 * 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 {BaseCallback, configureCallbacks, History, ModelLoggingVerbosity, standardizeCallbacks} 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 { disposeTensorsInLogs, UnresolvedLogs } from '../logs';\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, 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 `${exceptionPrefix} expected a batch of elements where each ` +\n `example has shape [${shapes[i].slice(1, shapes[i].length)}] ` +\n `(i.e.,tensor shape [*,${\n shapes[i].slice(1, shapes[i].length)}])` +\n ` but the ${exceptionPrefix} received an input with ${\n array.shape[0]}` +\n ` examples, each with shape [${\n array.shape.slice(1, array.shape.length)}]` +\n ` (tensor shape [${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|\n {[outputName: string]: string | LossOrMetricFn},\n outputNames: string[]): Array> {\n if (metrics == null || Array.isArray(metrics) && metrics.length === 0) {\n return outputNames.map(name => []);\n }\n\n let wrappedMetrics: Array|\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|\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);\n } else {\n // In this case, metrics is a dict.\n const nestedMetrics: Array> = [];\n for (const name of outputNames) {\n let outputMetrics: string|LossOrMetricFn|Array =\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|\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|\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;\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) => {\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 {\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 : [outputs]);\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 {\n if (this.isTraining) {\n throw new Error(\n 'Cannot start training because another fit() call is ongoing.');\n }\n this.isTraining = true;\n let inputs: Tensor[];\n let targets: Tensor[];\n let originalInputs: Tensor[];\n let originalTargets: 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 this.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 this.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 originalInputs = inputs;\n inputs = sliceArrays(inputs, 0, splitAt) as Tensor[];\n valY = sliceArrays(targets, splitAt, originalBatchSize) as Tensor[];\n originalTargets = targets;\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 this.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 = this.makeTrainFunction();\n const outLabels = this.getDedupedMetricsNames();\n\n let valFunction: (data: Tensor[]) => Scalar[];\n let callbackMetrics: string[];\n if (doValidation) {\n this.makeTestFunction();\n valFunction = this.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 this.fitLoop(\n 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 this.isTraining = false;\n // Memory clean up.\n disposeNewTensors(inputs, x);\n disposeNewTensors(targets, y);\n disposeNewTensors(originalInputs, x);\n disposeNewTensors(originalTargets, 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 * 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 */\n async fitLoop(\n f: (data: Tensor[]) => Scalar[], ins: Tensor[], outLabels?:\n string[], batchSize?: number, epochs?: number, verbose?: number,\n callbacks?: BaseCallback[], valF?: (data: Tensor[]) => Scalar[], valIns?:\n Tensor[], shuffle?: boolean|string, callbackMetrics?: string[],\n initialEpoch?: number, stepsPerEpoch?: number, validationSteps?: number):\n Promise {\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 this.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,\n stepsPerEpoch, batchSize, doValidation, callbackMetrics);\n callbackList.setModel(this);\n this.history = history;\n await callbackList.onTrainBegin();\n this.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'\n + ' 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 = K.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 = this.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 (this.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 (this.stopTraining_) {\n break;\n }\n }\n await callbackList.onTrainEnd();\n\n await this.history.syncData();\n return this.history;\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(dataset: Dataset, args: ModelFitDatasetArgs):\n Promise {\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 metric 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 data. It could be either a `tf.Tensor` or 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 {\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 disposeNewTensors(standardizeOut[0], x);\n disposeNewTensors(standardizeOut[1], y);\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 override 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 {\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 override 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/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 {\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 composed of Layer objects, including its topology and optionally\n * weights. See the Tutorial named \"How to import a Keras Model\" for usage\n * examples.\n *\n * This method is applicable to:\n *\n * 1. Models created with the `tf.layers.*`, `tf.sequential`, and\n * `tf.model` APIs of TensorFlow.js and later saved with the\n * `tf.LayersModel.save` method.\n * 2. Models converted from Keras or TensorFlow tf.keras using the\n * [tensorflowjs_converter](https://github.com/tensorflow/tfjs/tree/master/tfjs-converter).\n *\n * This mode is *not* applicable to TensorFlow `SavedModel`s or their converted\n * forms. For those models, use `tf.loadGraphModel`.\n *\n * Example 1. Load a model from an HTTP server.\n *\n * ```js\n * const model = await tf.loadLayersModel(\n * 'https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json');\n * model.summary();\n * ```\n *\n * Example 2: Save `model`'s topology and weights to browser [local\n * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);\n * then load it back.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('localstorage://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 3. Saving `model`'s topology and weights to browser\n * [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);\n * then load it back.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('indexeddb://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 4. Load a model from user-selected files from HTML\n * [file input\n * elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file).\n *\n * ```js\n * // Note: this code snippet will not work without the HTML elements in the\n * // page\n * const jsonUpload = document.getElementById('json-upload');\n * const weightsUpload = document.getElementById('weights-upload');\n *\n * const model = await tf.loadLayersModel(\n * tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));\n * ```\n *\n * @param pathOrIOHandler Can be either of the two formats\n * 1. A string path to the `ModelAndWeightsConfig` JSON describing\n * the model in the canonical TensorFlow.js format. For file://\n * (tfjs-node-only), http:// and https:// schemas, the path can be\n * either absolute or relative. The content of the JSON file is assumed to\n * be a JSON object with the 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. A `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 *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport async function loadLayersModel(\n pathOrIOHandler: string|io.IOHandler,\n options?: io.LoadOptions): Promise {\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 {\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 weightData: io.WeightData, specs: io.WeightsManifestEntry[]):\n {modelWeights: NamedTensorMap, optimizerWeights: NamedTensor[]} {\n const name2Tensor = io.decodeWeights(weightData, 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override async evaluateDataset(dataset: Dataset<{}>,\n args: ModelEvaluateDatasetArgs): Promise {\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 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([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 override predict(x: Tensor|Tensor[], args: ModelPredictArgs = {}):\n 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 override 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 override 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 override get optimizer(): Optimizer {\n return this.model == null ? undefined : this.model.optimizer;\n }\n\n override 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 override async fit(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|{[inputName: string]: Tensor},\n args: ModelFitArgs = {}): Promise {\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 override async fitDataset(dataset: Dataset,\n args: ModelFitDatasetArgs): Promise {\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 metric 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 data. It could be either a `tf.Tensor` or 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 override async trainOnBatch(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|\n {[inputName: string]: Tensor}): Promise {\n return this.model.trainOnBatch(x, y);\n }\n\n /* See parent class for JsDoc */\n /** @nocollapse */\n static override fromConfig(\n cls: serialization.SerializableConstructor,\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 override 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 override 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 override getConfig(): any {\n // NOTE(cais): We override the return type of getConfig() to `any` here,\n // because the `Sequential` class is a special case among `Container`\n // subtypes in that its getConfig() method returns an Array (not a\n // dict).\n const layers: serialization.ConfigDict[] = [];\n for (const layer of this.layers) {\n const dict: serialization.ConfigDict = {};\n dict['className'] = layer.getClassName();\n dict['config'] = layer.getConfig();\n layers.push(dict);\n }\n return {name: this.name, layers};\n }\n}\nserialization.registerClass(Sequential);\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Exported functions.\n */\n\nimport {BaseCallbackConstructor, CallbackConstructorRegistry} from './base_callbacks';\nimport {ContainerArgs} from './engine/container';\nimport {Input, InputConfig,} from './engine/input_layer';\nimport {SymbolicTensor} from './engine/topology';\nimport {LayersModel} from './engine/training';\nimport {Sequential, SequentialArgs} from './models';\n\nexport {loadLayersModel} from './models';\n\n// TODO(cais): Add doc string to all the public static functions in this\n// class; include exectuable JavaScript code snippets where applicable\n// (b/74074458).\n\n// LayersModel and related factory methods.\n\n/**\n * A model is a data structure that consists of `Layers` and defines inputs\n * and outputs.\n *\n * The key difference between `tf.model` and `tf.sequential` is that\n * `tf.model` is more generic, supporting an arbitrary graph (without\n * cycles) of layers. `tf.sequential` is less generic and supports only a linear\n * stack of layers.\n *\n * When creating a `tf.LayersModel`, specify its input(s) and output(s). Layers\n * are used to wire input(s) to output(s).\n *\n * For example, the following code snippet defines a model consisting of\n * two `dense` layers, with 10 and 4 units, respectively.\n *\n * ```js\n * // Define input, which has a size of 5 (not including batch dimension).\n * const input = tf.input({shape: [5]});\n *\n * // First dense layer uses relu activation.\n * const denseLayer1 = tf.layers.dense({units: 10, activation: 'relu'});\n * // Second dense layer uses softmax activation.\n * const denseLayer2 = tf.layers.dense({units: 4, activation: 'softmax'});\n *\n * // Obtain the output symbolic tensor by applying the layers on the input.\n * const output = denseLayer2.apply(denseLayer1.apply(input));\n *\n * // Create the model based on the inputs.\n * const model = tf.model({inputs: input, outputs: output});\n *\n * // The model can be used for training, evaluation and prediction.\n * // For example, the following line runs prediction with the model on\n * // some fake data.\n * model.predict(tf.ones([2, 5])).print();\n * ```\n * See also:\n * `tf.sequential`, `tf.loadLayersModel`.\n *\n * @doc {heading: 'Models', subheading: 'Creation'}\n */\nexport function model(args: ContainerArgs): LayersModel {\n return new LayersModel(args);\n}\n\n/**\n * Creates a `tf.Sequential` model. A sequential model is any model where the\n * outputs of one layer are the inputs to the next layer, i.e. the model\n * topology is a simple 'stack' of layers, with no branching or skipping.\n *\n * This means that the first layer passed to a `tf.Sequential` model should have\n * a defined input shape. What that means is that it should have received an\n * `inputShape` or `batchInputShape` argument, or for some type of layers\n * (recurrent, Dense...) an `inputDim` argument.\n *\n * The key difference between `tf.model` and `tf.sequential` is that\n * `tf.sequential` is less generic, supporting only a linear stack of layers.\n * `tf.model` is more generic and supports an arbitrary graph (without\n * cycles) of layers.\n *\n * Examples:\n *\n * ```js\n * const model = tf.sequential();\n *\n * // First layer must have an input shape defined.\n * model.add(tf.layers.dense({units: 32, inputShape: [50]}));\n * // Afterwards, TF.js does automatic shape inference.\n * model.add(tf.layers.dense({units: 4}));\n *\n * // Inspect the inferred shape of the model's output, which equals\n * // `[null, 4]`. The 1st dimension is the undetermined batch dimension; the\n * // 2nd is the output size of the model's last layer.\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * It is also possible to specify a batch size (with potentially undetermined\n * batch dimension, denoted by \"null\") for the first layer using the\n * `batchInputShape` key. The following example is equivalent to the above:\n *\n * ```js\n * const model = tf.sequential();\n *\n * // First layer must have a defined input shape\n * model.add(tf.layers.dense({units: 32, batchInputShape: [null, 50]}));\n * // Afterwards, TF.js does automatic shape inference.\n * model.add(tf.layers.dense({units: 4}));\n *\n * // Inspect the inferred shape of the model's output.\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * You can also use an `Array` of already-constructed `Layer`s to create\n * a `tf.Sequential` model:\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 32, inputShape: [50]}),\n * tf.layers.dense({units: 4})]\n * });\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * @doc {heading: 'Models', subheading: 'Creation'}\n */\nexport function sequential(config?: SequentialArgs): Sequential {\n return new Sequential(config);\n}\n\n/**\n * Used to instantiate an input to a model as a `tf.SymbolicTensor`.\n *\n * Users should call the `input` factory function for\n * consistency with other generator functions.\n *\n * Example:\n *\n * ```js\n * // Defines a simple logistic regression model with 32 dimensional input\n * // and 3 dimensional output.\n * const x = tf.input({shape: [32]});\n * const y = tf.layers.dense({units: 3, activation: 'softmax'}).apply(x);\n * const model = tf.model({inputs: x, outputs: y});\n * model.predict(tf.ones([2, 32])).print();\n * ```\n *\n * Note: `input` is only necessary when using `model`. When using\n * `sequential`, specify `inputShape` for the first layer or use `inputLayer`\n * as the first layer.\n *\n * @doc {heading: 'Models', subheading: 'Inputs'}\n */\nexport function input(config: InputConfig): SymbolicTensor {\n return Input(config);\n}\n\nexport function registerCallbackConstructor(\n verbosityLevel: number,\n callbackConstructor: BaseCallbackConstructor): void {\n CallbackConstructorRegistry.registerCallbackConstructor(\n verbosityLevel, callbackConstructor);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n// Layer activation functions\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\nimport * as K from './backend/tfjs_backend';\nimport {ActivationIdentifier} from './keras_format/activation_config';\nimport {deserializeKerasObject} from './utils/generic_utils';\n\n/**\n * Base class for Activations.\n *\n * Special note: due to cross-language compatibility reasons, the\n * static readonly className field in this family of classes must be set to\n * the initialLowerCamelCase name of the activation.\n */\nexport abstract class Activation extends serialization.Serializable {\n abstract apply(tensor: Tensor, axis?: number): Tensor;\n getConfig(): serialization.ConfigDict {\n return {};\n }\n}\n\n/**\n * Exponential linear unit (ELU).\n * Reference: https://arxiv.org/abs/1511.07289\n */\nexport class Elu extends Activation {\n /** @nocollapse */\n static readonly className = 'elu';\n /**\n * Calculate the activation function.\n *\n * @param x: Input.\n * @param alpha: Scaling factor the negative section.\n * @return Output of the ELU activation.\n */\n apply(x: Tensor, alpha = 1): Tensor {\n return K.elu(x, alpha);\n }\n}\nserialization.registerClass(Elu);\n\n/**\n * Scaled Exponential Linear Unit. (Klambauer et al., 2017).\n * Reference: Self-Normalizing Neural Networks, https://arxiv.org/abs/1706.02515\n * Notes:\n * - To be used together with the initialization \"lecunNormal\".\n * - To be used together with the dropout variant \"AlphaDropout\".\n */\nexport class Selu extends Activation {\n /** @nocollapse */\n static readonly className = 'selu';\n apply(x: Tensor): Tensor {\n return tfc.selu(x);\n }\n}\nserialization.registerClass(Selu);\n\n/**\n * Rectified linear unit\n */\nexport class Relu extends Activation {\n /** @nocollapse */\n static readonly className = 'relu';\n apply(x: Tensor): Tensor {\n return tfc.relu(x);\n }\n}\nserialization.registerClass(Relu);\n\n/**\n * Rectified linear unit activation maxing out at 6.0.\n */\nexport class Relu6 extends Activation {\n /** @nocollapse */\n static readonly className = 'relu6';\n apply(x: Tensor): Tensor {\n return tidy(() => tfc.minimum(6.0, tfc.relu(x)));\n }\n}\nserialization.registerClass(Relu6);\n\n//* Linear activation (no-op) */\nexport class Linear extends Activation {\n /** @nocollapse */\n static readonly className = 'linear';\n apply(x: Tensor): Tensor {\n return x;\n }\n}\nserialization.registerClass(Linear);\n\n/**\n * Sigmoid activation function.\n */\nexport class Sigmoid extends Activation {\n /** @nocollapse */\n static readonly className = 'sigmoid';\n apply(x: Tensor): Tensor {\n return tfc.sigmoid(x);\n }\n}\nserialization.registerClass(Sigmoid);\n\n/**\n * Segment-wise linear approximation of sigmoid.\n */\nexport class HardSigmoid extends Activation {\n /** @nocollapse */\n static readonly className = 'hardSigmoid';\n apply(x: Tensor): Tensor {\n return K.hardSigmoid(x);\n }\n}\nserialization.registerClass(HardSigmoid);\n\n/**\n * Softplus activation function.\n */\nexport class Softplus extends Activation {\n /** @nocollapse */\n static readonly className = 'softplus';\n apply(x: Tensor): Tensor {\n return tfc.softplus(x);\n }\n}\nserialization.registerClass(Softplus);\n\n/**\n * Softsign activation function.\n */\nexport class Softsign extends Activation {\n /** @nocollapse */\n static readonly className = 'softsign';\n apply(x: Tensor): Tensor {\n return K.softsign(x);\n }\n}\nserialization.registerClass(Softsign);\n\n/**\n * Hyperbolic tangent function.\n */\nexport class Tanh extends Activation {\n /** @nocollapse */\n static readonly className = 'tanh';\n apply(x: Tensor): Tensor {\n return tfc.tanh(x);\n }\n}\nserialization.registerClass(Tanh);\n\n/**\n * Softmax activation function\n */\nexport class Softmax extends Activation {\n /** @nocollapse */\n static readonly className = 'softmax';\n /**\n * Calculate the activation function.\n *\n * @param x Tensor.\n * @param axis Integer, axis along which the softmax normalization is applied.\n * Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be\n * an error.\n *\n * @returns a Tensor of the same shape as x\n *\n * @throws ValueError: In case `dim(x) < 2`.\n */\n apply(x: Tensor, axis: number = (-1)): Tensor {\n return tfc.softmax(x, axis);\n }\n}\nserialization.registerClass(Softmax);\n\n/**\n * Log softmax activation function\n */\nexport class LogSoftmax extends Activation {\n /** @nocollapse */\n static readonly className = 'logSoftmax';\n /**\n * Calculate the activation function of log softmax:\n * log( exp(x_i) / sum(exp(x)) )\n *\n * @param x Tensor.\n * @param axis Integer, axis along which the softmax normalization is applied.\n * Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be\n * an error.\n *\n * @returns a Tensor of the same shape as x\n *\n * @throws ValueError: In case `dim(x) < 2`.\n */\n apply(x: Tensor, axis: number = (-1)): Tensor {\n return tfc.logSoftmax(x, axis);\n }\n}\nserialization.registerClass(LogSoftmax);\n\n/**\n * Swish activation function\n */\nexport class Swish extends Activation {\n /** @nocollapse */\n static readonly className = 'swish';\n /**\n * Calculate the activation function.\n *\n * @param x Tensor.\n * @param alpha Scaling factor for the sigmoid function.\n * @returns a Tensor of the same shape as x\n */\n apply(x: Tensor, alpha = 1): Tensor {\n return tidy(() => tfc.mul(tfc.sigmoid(tfc.mul(x, alpha)), x));\n }\n}\nserialization.registerClass(Swish);\n\n/**\n * Mish activation function\n */\nexport class Mish extends Activation {\n /** @nocollapse */\n static readonly className = 'mish';\n /**\n * Calculate the activation function.\n *\n * @param x Tensor.\n * @returns a Tensor of the same shape as x\n */\n apply(x: Tensor): Tensor {\n return tidy(() => tfc.mul(x, tfc.tanh(tfc.softplus(x))));\n }\n}\nserialization.registerClass(Mish);\n\nexport function serializeActivation(activation: Activation): string {\n return activation.getClassName();\n}\n\nexport function deserializeActivation(\n config: serialization.ConfigDict,\n customObjects: serialization.ConfigDict = {}): Activation {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'activation');\n}\n\nexport function getActivation(identifier: ActivationIdentifier|\n serialization.ConfigDict|Activation): Activation {\n if (identifier == null) {\n const config: serialization.ConfigDict = {};\n config['className'] = 'linear';\n config['config'] = {};\n return deserializeActivation(config);\n }\n if (typeof identifier === 'string') {\n const config: serialization.ConfigDict = {};\n config['className'] = identifier;\n config['config'] = {};\n return deserializeActivation(config);\n } else if (identifier instanceof Activation) {\n return identifier;\n } else {\n return deserializeActivation(identifier);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* original source: keras/regularizers.py */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {abs, add, Scalar, serialization, sum, Tensor, tidy, zeros} from '@tensorflow/tfjs-core';\nimport * as K from './backend/tfjs_backend';\nimport {deserializeKerasObject, serializeKerasObject} from './utils/generic_utils';\n\nfunction assertObjectArgs(args: L1Args|L2Args|L1L2Args): void {\n if (args != null && typeof args !== 'object') {\n throw new Error(\n `Argument to L1L2 regularizer's constructor is expected to be an ` +\n `object, but received: ${args}`);\n }\n}\n\n/**\n * Regularizer base class.\n */\nexport abstract class Regularizer extends serialization.Serializable {\n abstract apply(x: Tensor): Scalar;\n}\n\nexport interface L1L2Args {\n /** L1 regularization rate. Defaults to 0.01. */\n l1?: number;\n /** L2 regularization rate. Defaults to 0.01. */\n l2?: number;\n}\n\nexport interface L1Args {\n /** L1 regularization rate. Defaults to 0.01. */\n l1: number;\n}\n\nexport interface L2Args {\n /** L2 regularization rate. Defaults to 0.01. */\n l2: number;\n}\n\nexport class L1L2 extends Regularizer {\n /** @nocollapse */\n static className = 'L1L2';\n\n private readonly l1: number;\n private readonly l2: number;\n private readonly hasL1: boolean;\n private readonly hasL2: boolean;\n constructor(args?: L1L2Args) {\n super();\n\n assertObjectArgs(args);\n\n this.l1 = args == null || args.l1 == null ? 0.01 : args.l1;\n this.l2 = args == null || args.l2 == null ? 0.01 : args.l2;\n this.hasL1 = this.l1 !== 0;\n this.hasL2 = this.l2 !== 0;\n }\n\n /**\n * Porting note: Renamed from __call__.\n * @param x Variable of which to calculate the regularization score.\n */\n apply(x: Tensor): Scalar {\n return tidy(() => {\n let regularization: Tensor = zeros([1]);\n if (this.hasL1) {\n regularization = add(regularization, sum(tfc.mul(this.l1, abs(x))));\n }\n if (this.hasL2) {\n regularization =\n add(regularization, sum(tfc.mul(this.l2, K.square(x))));\n }\n return tfc.reshape(regularization, []);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n return {'l1': this.l1, 'l2': this.l2};\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: serialization.SerializableConstructor,\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 {add, cast, clipByValue, elu, exp, greater, leakyRelu, logSumExp, mul, ones, prelu, relu, scalar, serialization, sub, Tensor, tidy} 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 override 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 override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const x = getExactlyOneTensor(inputs);\n return leakyRelu(x, this.alpha);\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override 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 override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n inputs = getExactlyOneTensor(inputs);\n return prelu(inputs, this.alpha.read());\n }\n\n override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const x = getExactlyOneTensor(inputs);\n return elu(x);\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override 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 override 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 override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override 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|number[];\n}\n\nexport class Softmax extends Layer {\n /** @nocollapse */\n static className = 'Softmax';\n readonly axis: number|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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n // TODO(pforderique): Add tests for when `this.axis` is a number[].\n return tidy(() => {\n let x = getExactlyOneTensor(inputs);\n const mask = kwargs['mask'] as Tensor;\n if (mask != null) {\n // Since mask is 1.0 for positions we want to keep and 0.0 for masked\n // positions, this operation will create a tensor which is 0.0 for\n // positions we want to attend and -1e.9 for masked positions.\n const adder =\n mul(sub(ones(x.shape), cast(mask, x.dtype)), scalar(-1e9));\n\n // Since we are adding it to the raw scores before the softmax, this\n // is effectively the same as removing these entirely.\n x = add(x, adder);\n }\n if (this.axis instanceof Array) {\n if (this.axis.length > 1) {\n return exp(sub(x, logSumExp(x, this.axis, true)));\n } else {\n return this.softmax(x, this.axis[0]);\n }\n }\n return this.softmax(x, this.axis);\n });\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override 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,\n kernel as tfc.Tensor, 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 override 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 override 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 override 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 override 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 override 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 override 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 override getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n return config;\n }\n\n protected static override 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 override getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n return config;\n }\n\n protected static override 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 override className = 'Conv2DTranspose';\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 override 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 override 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 override 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 override 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 override className = 'Conv3DTranspose';\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 override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tfc.tidy(() => {\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 override 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 override 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 override 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 override 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 override 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 override 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 override getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n delete config['dataFormat'];\n return config;\n }\n\n protected static override 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 lists 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 override 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 override 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 override 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 override 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 override 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 override getConfig(): serialization.ConfigDict {\n const config = {\n size: this.size,\n dataFormat: this.dataFormat,\n interpolation: this.interpolation\n };\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 * Regularizer 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 override 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 override 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 override 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 override 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';\n\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\n * memory-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 override 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 override 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 override 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 override 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 override 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 = [];\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 override 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 override 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 override 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 override setFastWeightInitDuringBuild(value: boolean) {\n super.setFastWeightInitDuringBuild(value);\n if (this.cell != null) {\n this.cell.setFastWeightInitDuringBuild(value);\n }\n }\n\n override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 * Constraint function 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 /**\n * This is added for test DI purpose.\n */\n dropoutFunc?: Function;\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 readonly dropoutFunc: Function;\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.dropoutFunc = args.dropoutFunc;\n this.stateSize = this.units;\n this.dropoutMask = null;\n this.recurrentDropoutMask = null;\n }\n\n override 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 override 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 dropoutFunc: this.dropoutFunc,\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 dropoutFunc: this.dropoutFunc,\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 override 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 * This is added for test DI purpose.\n */\n dropoutFunc?: Function;\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 override 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 override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 readonly dropoutFunc: Function;\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.dropoutFunc = args.dropoutFunc;\n this.implementation = args.implementation;\n this.stateSize = this.units;\n this.dropoutMask = null;\n this.recurrentDropoutMask = null;\n }\n\n public override 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 override 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 dropoutFunc: this.dropoutFunc,\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 dropoutFunc: this.dropoutFunc,\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 override 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 override 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 override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 readonly dropoutFunc: Function;\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.dropoutFunc = args.dropoutFunc;\n this.implementation = args.implementation;\n this.stateSize = [this.units, this.units];\n this.dropoutMask = null;\n this.recurrentDropoutMask = null;\n }\n\n public override 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 override 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 dropoutFunc: this.dropoutFunc\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 dropoutFunc: this.dropoutFunc\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 override 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 override 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 override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 * An `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 override 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 override 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 override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 override 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 override 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 override 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 override 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 dropoutFunc?: Function,\n}): tfc.Tensor|tfc.Tensor[] {\n const {ones, rate, training = false, count = 1, dropoutFunc} = args;\n\n const droppedInputs = () =>\n dropoutFunc != null ? dropoutFunc(ones(), rate) : 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 {\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 override className = 'ConvRNN2D';\n\n declare 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 override 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 override 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 override 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 override 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, ConvRNN2DCellArgs {}\n\nexport class ConvLSTM2DCell extends LSTMCell implements ConvRNN2DCell {\n /** @nocollapse */\n static override 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 override 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 override 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 dropoutFunc: this.dropoutFunc\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 dropoutFunc: this.dropoutFunc\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 override 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, ConvRNN2DLayerArgs {}\n\nexport class ConvLSTM2D extends ConvRNN2D {\n /** @nocollapse */\n static override 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 override fromConfig(\n cls: tfc.serialization.SerializableConstructor,\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 override 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 override 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 override 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 override className = 'SpatialDropout1D';\n\n constructor(args: SpatialDropout1DLayerConfig) {\n super(args);\n this.inputSpec = [{ndim: 3}];\n }\n\n protected override 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 override 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 override 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 override 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 override 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: channelsLast (default) or channelsFirst. */\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 override 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 override 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 override 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 override 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 override 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 override computeOutputShape(inputShape: Shape): Shape {\n return [inputShape[0], this.n, inputShape[1]];\n }\n\n override 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 override 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 override 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 override 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 override 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 override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return transpose(getExactlyOneTensor(inputs), this.dimsIncludingBatch);\n }\n\n override 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 override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override getConfig() {\n const baseConfig = super.getConfig();\n const config = {maskValue: this.maskValue};\n Object.assign(config, baseConfig);\n return config;\n }\n\n override computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]):\n Tensor {\n const input = getExactlyOneTensor(inputs);\n const axis = -1;\n return any(notEqual(input, this.maskValue), axis);\n }\n\n override 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 override 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 override warnOnIncompatibleInputShape(inputShape: Shape) {}\n\n override computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]):\n 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 override 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 override 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 override 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 override 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 override 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 override 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 override computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]):\n 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 override 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 override 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 override 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 override 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 override 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 override 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 override mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n return K.concatenate(inputs, this.axis);\n });\n }\n\n override 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 override computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]):\n 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 override 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 is the 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 override 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 override 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 override 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 override computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]):\n Tensor {\n return null;\n }\n\n override 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","/**\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: Noise Layers.\n */\n\nimport {add, greaterEqual, mul, randomUniform, serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\n\nimport * as K from '../backend/tfjs_backend';\nimport {Layer, LayerArgs} from '../engine/topology';\nimport {Shape} from '../keras_format/common';\nimport {Kwargs} from '../types';\nimport {getExactlyOneTensor} from '../utils/types_utils';\n\nexport declare interface GaussianNoiseArgs extends LayerArgs {\n /** Standard Deviation. */\n stddev: number;\n}\n\nexport class GaussianNoise extends Layer {\n /** @nocollapse */\n static className = 'GaussianNoise';\n readonly stddev: number;\n\n constructor(args: GaussianNoiseArgs) {\n super(args);\n this.supportsMasking = true;\n this.stddev = args.stddev;\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override getConfig() {\n const baseConfig = super.getConfig();\n const config = {stddev: this.stddev};\n Object.assign(config, baseConfig);\n return config;\n }\n\n override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n const input = getExactlyOneTensor(inputs);\n const noised = () =>\n add(K.randomNormal(input.shape, 0, this.stddev), input);\n const output =\n K.inTrainPhase(noised, () => input, kwargs['training'] || false);\n return output;\n });\n }\n}\nserialization.registerClass(GaussianNoise);\n\nexport declare interface GaussianDropoutArgs extends LayerArgs {\n /** drop probability. */\n rate: number;\n}\n\nexport class GaussianDropout extends Layer {\n /** @nocollapse */\n static className = 'GaussianDropout';\n readonly rate: number;\n\n constructor(args: GaussianDropoutArgs) {\n super(args);\n this.supportsMasking = true;\n this.rate = args.rate;\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override getConfig() {\n const baseConfig = super.getConfig();\n const config = {rate: this.rate};\n Object.assign(config, baseConfig);\n return config;\n }\n\n override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n const input = getExactlyOneTensor(inputs);\n if (this.rate > 0 && this.rate < 1) {\n const noised = () => {\n const stddev = Math.sqrt(this.rate / (1 - this.rate));\n return mul(input, K.randomNormal(input.shape, 1, stddev));\n };\n return K.inTrainPhase(noised, () => input, kwargs['training'] || false);\n }\n return input;\n });\n }\n}\nserialization.registerClass(GaussianDropout);\n\nexport declare interface AlphaDropoutArgs extends LayerArgs {\n /** drop probability. */\n rate: number;\n /**\n * A 1-D `Tensor` of type `int32`, representing the\n * shape for randomly generated keep/drop flags.\n */\n noiseShape?: Shape;\n}\n\n/**\n * Applies Alpha Dropout to the input.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * Alpha Dropout is a `Dropout` that keeps mean and variance of inputs\n * to their original values, in order to ensure the self-normalizing property\n * even after this dropout.\n * Alpha Dropout fits well to Scaled Exponential Linear Units\n * by randomly setting activations to the negative saturation value.\n *\n * Arguments:\n * - `rate`: float, drop probability (as with `Dropout`).\n * The multiplicative noise will have\n * standard deviation `sqrt(rate / (1 - rate))`.\n * - `noise_shape`: A 1-D `Tensor` of type `int32`, representing the\n * shape for randomly generated keep/drop flags.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\n */\nexport class AlphaDropout extends Layer {\n /** @nocollapse */\n static className = 'AlphaDropout';\n readonly rate: number;\n readonly noiseShape: Shape;\n\n constructor(args: AlphaDropoutArgs) {\n super(args);\n this.supportsMasking = true;\n this.rate = args.rate;\n this.noiseShape = args.noiseShape;\n }\n\n _getNoiseShape(inputs: Tensor|Tensor[]) {\n return this.noiseShape || getExactlyOneTensor(inputs).shape;\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n override getConfig() {\n const baseConfig = super.getConfig();\n const config = {rate: this.rate};\n Object.assign(config, baseConfig);\n return config;\n }\n\n override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n if (this.rate < 1 && this.rate > 0) {\n const noiseShape = this._getNoiseShape(inputs);\n\n const droppedInputs = () => {\n const input = getExactlyOneTensor(inputs);\n\n const alpha = 1.6732632423543772848170429916717;\n const scale = 1.0507009873554804934193349852946;\n\n const alphaP = -alpha * scale;\n\n let keptIdx = greaterEqual(randomUniform(noiseShape), this.rate);\n\n keptIdx = K.cast(keptIdx, 'float32'); // get default dtype.\n\n // Get affine transformation params.\n const a = ((1 - this.rate) * (1 + this.rate * alphaP ** 2)) ** -0.5;\n const b = -a * alphaP * this.rate;\n\n // Apply mask.\n const x = add(mul(input, keptIdx), mul(add(keptIdx, -1), alphaP));\n\n return add(mul(x, a), b);\n };\n return K.inTrainPhase(\n droppedInputs, () => getExactlyOneTensor(inputs),\n kwargs['training'] || false);\n }\n return inputs;\n });\n }\n}\nserialization.registerClass(AlphaDropout);\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 override 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 override 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 override 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 override 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 override 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 return tfc.reshape(v, broadcastShape);\n } else {\n return v;\n }\n };\n\n let scale = this.scale ? broadcast(this.gamma.read()) : null;\n let offset = this.center ? broadcast(this.beta.read()) : null;\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 if (scale != null) {\n scale = tfc.tile(scale, scaleOffsetTiling);\n }\n if (offset != null) {\n offset = tfc.tile(offset, scaleOffsetTiling);\n }\n\n return batchNormalization(\n input, mean, variance, offset, scale, this.epsilon);\n });\n }\n\n override 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 override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(\n () => spatial2dPadding(\n getExactlyOneTensor(inputs), this.padding, this.dataFormat));\n }\n\n override 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 strides 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 override 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 override 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 override 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 dimensions.\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 override 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 override 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 override 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 override 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 override 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 override 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 override computeOutputShape(inputShape: Shape): Shape {\n return [inputShape[0], inputShape[2]];\n }\n\n override 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 override 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 override 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 override 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 override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n throw new NotImplementedError();\n }\n\n override 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 override 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 override 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 override build(inputShape: Shape|Shape[]): void {\n this.built = true;\n }\n\n // TODO(cais): Implement activityRegularizer getter.\n\n override 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 override 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 override get trainableWeights(): LayerVariable[] {\n return this.layer.trainableWeights;\n }\n // TODO(cais): Implement setter for trainableWeights.\n\n override get nonTrainableWeights(): LayerVariable[] {\n return this.layer.nonTrainableWeights;\n }\n // TODO(cais): Implement setter for nonTrainableWeights.\n\n override 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 override get losses(): RegularizerFn[] {\n return this.layer.losses;\n }\n\n // TODO(cais): Implement getLossesFor().\n\n override getWeights(): Tensor[] {\n return this.layer.getWeights();\n }\n\n override setWeights(weights: Tensor[]): void {\n this.layer.setWeights(weights);\n }\n\n override 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 override setFastWeightInitDuringBuild(value: boolean) {\n super.setFastWeightInitDuringBuild(value);\n if (this.layer != null) {\n this.layer.setFastWeightInitDuringBuild(value);\n }\n }\n\n /** @nocollapse */\n static override fromConfig(\n cls: serialization.SerializableConstructor,\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 override 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 override 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 override 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 override get trainable(): boolean {\n return this._trainable;\n }\n\n override 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 override getWeights(): Tensor[] {\n return this.forwardLayer.getWeights().concat(\n this.backwardLayer.getWeights());\n }\n\n override 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 override 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 override 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 = [];\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)\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 override 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 override resetStates(states?: Tensor|Tensor[]): void {\n this.forwardLayer.resetStates();\n this.backwardLayer.resetStates();\n }\n\n override 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 override 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 override get trainableWeights(): LayerVariable[] {\n return this.forwardLayer.trainableWeights.concat(\n this.backwardLayer.trainableWeights);\n }\n\n override get nonTrainableWeights(): LayerVariable[] {\n return this.forwardLayer.nonTrainableWeights.concat(\n this.backwardLayer.nonTrainableWeights);\n }\n\n // TODO(cais): Implement constraints().\n\n override 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 override 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 override fromConfig(\n cls: serialization.SerializableConstructor,\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 2022 CodeSmith 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 {LayerArgs, Layer} from '../../engine/topology';\nimport { serialization, Tensor, mul, add, tidy } from '@tensorflow/tfjs-core';\nimport { getExactlyOneTensor } from '../../utils/types_utils';\nimport * as K from '../../backend/tfjs_backend';\nimport { Kwargs } from '../../types';\n\nexport declare interface RescalingArgs extends LayerArgs {\n scale: number;\n offset?: number;\n}\n\n/**\n * Preprocessing Rescaling Layer\n *\n * This rescales images by a scaling and offset factor\n */\nexport class Rescaling extends Layer {\n /** @nocollapse */\n static className = 'Rescaling';\n private readonly scale: number;\n private readonly offset: number;\n constructor(args: RescalingArgs) {\n super(args);\n\n this.scale = args.scale;\n\n if(args.offset) {\n this.offset = args.offset;\n } else {\n this.offset = 0;\n }\n }\n\n override getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'scale': this.scale,\n 'offset': this.offset\n };\n\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor[]|Tensor {\n return tidy(() => {\n inputs = getExactlyOneTensor(inputs);\n if(inputs.dtype !== 'float32') {\n inputs = K.cast(inputs, 'float32');\n }\n return add(mul(inputs, this.scale), this.offset);\n });\n }\n}\n\nserialization.registerClass(Rescaling);\n","/**\n * @license\n * Copyright 2022 CodeSmith 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 {serialization,DataType,unstack,stack,tensor,Tensor,Tensor1D,Tensor2D, Tensor3D, Tensor4D, tidy, range, image} from '@tensorflow/tfjs-core';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../../utils/types_utils';\nimport {LayerArgs, Layer} from '../../engine/topology';\nimport {Kwargs} from '../../types';\nimport {Shape} from '../../keras_format/common';\nimport * as K from '../../backend/tfjs_backend';\n\nconst {resizeBilinear, cropAndResize} = image;\n\nexport declare interface CenterCropArgs extends LayerArgs{\n height: number;\n width: number;\n}\n\nexport class CenterCrop extends Layer {\n /** @nocollapse */\n static className = 'CenterCrop';\n private readonly height: number;\n private readonly width: number;\n constructor(args: CenterCropArgs) {\n super(args);\n this.height = args.height;\n this.width = args.width;\n }\n\n centerCrop(inputs: Tensor3D | Tensor4D, hBuffer: number, wBuffer: number,\n height: number, width: number, inputHeight: number,\n inputWidth: number, dtype: DataType): Tensor | Tensor[] {\n\n return tidy(() => {\n let input: Tensor4D;\n let isRank3 = false;\n const top = hBuffer / inputHeight;\n const left = wBuffer / inputWidth;\n const bottom = ((height) + hBuffer) / inputHeight;\n const right = ((width) + wBuffer) / inputWidth;\n const bound = [top, left, bottom, right];\n const boxesArr = [];\n\n if(inputs.rank === 3) {\n isRank3 = true;\n input = stack([inputs]) as Tensor4D;\n } else {\n input = inputs as Tensor4D;\n }\n\n for (let i = 0; i < input.shape[0]; i++) {\n boxesArr.push(bound);\n }\n\n const boxes: Tensor2D = tensor(boxesArr, [boxesArr.length, 4]);\n const boxInd: Tensor1D = range(0, boxesArr.length, 1, 'int32');\n\n const cropSize: [number, number] = [height, width];\n const cropped = cropAndResize(input, boxes, boxInd, cropSize, 'nearest');\n\n if(isRank3) {\n return K.cast(getExactlyOneTensor(unstack(cropped)), dtype);\n }\n return K.cast(cropped, dtype);\n });\n\n }\n\n upsize(inputs : Tensor3D | Tensor4D, height: number,\n width: number, dtype: DataType): Tensor | Tensor[] {\n\n return tidy(() => {\n const outputs = resizeBilinear(inputs, [height, width]);\n return K.cast(outputs, dtype);\n });\n\n}\n\n override call(inputs: Tensor3D | Tensor4D , kwargs: Kwargs):\n Tensor[] | Tensor {\n return tidy(() => {\n const rankedInputs = getExactlyOneTensor(inputs) as Tensor3D | Tensor4D;\n const dtype = rankedInputs.dtype;\n const inputShape = rankedInputs.shape;\n const inputHeight = inputShape[inputShape.length - 3];\n const inputWidth = inputShape[inputShape.length - 2];\n\n let hBuffer = 0;\n if (inputHeight !== this.height) {\n hBuffer = Math.floor((inputHeight - this.height) / 2);\n }\n\n let wBuffer = 0;\n if (inputWidth !== this.width) {\n wBuffer = Math.floor((inputWidth - this.width) / 2);\n\n if (wBuffer === 0) {\n wBuffer = 1;\n }\n }\n\n if(hBuffer >= 0 && wBuffer >= 0) {\n return this.centerCrop(rankedInputs, hBuffer, wBuffer,\n this.height, this.width, inputHeight,\n inputWidth, dtype);\n } else {\n return this.upsize(inputs, this.height, this.width, dtype);\n }\n });\n\n }\n\n override getConfig(): serialization.ConfigDict{\n\n const config: serialization.ConfigDict = {\n 'height' : this.height,\n 'width' : this.width\n };\n\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n override computeOutputShape(inputShape: Shape | Shape[]): Shape | Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const hAxis = inputShape.length - 3;\n const wAxis = inputShape.length - 2;\n inputShape[hAxis] = this.height;\n inputShape[wAxis] = this.width;\n return inputShape;\n }\n}\n\nserialization.registerClass(CenterCrop);\n","/**\n * @license\n * Copyright 2022 CodeSmith 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 { LayerArgs, Layer } from '../../engine/topology';\nimport { serialization, Tensor, tidy, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\nimport { greater, greaterEqual, max, min} from '@tensorflow/tfjs-core';\nimport { Shape } from '../../keras_format/common';\nimport { getExactlyOneShape, getExactlyOneTensor } from '../../utils/types_utils';\nimport { Kwargs } from '../../types';\nimport { ValueError } from '../../errors';\nimport * as K from '../../backend/tfjs_backend';\nimport * as utils from './preprocessing_utils';\nimport { OutputMode } from './preprocessing_utils';\n\nexport declare interface CategoryEncodingArgs extends LayerArgs {\n numTokens: number;\n outputMode?: OutputMode;\n }\n\nexport class CategoryEncoding extends Layer {\n /** @nocollapse */\n static className = 'CategoryEncoding';\n private readonly numTokens: number;\n private readonly outputMode: OutputMode;\n\n constructor(args: CategoryEncodingArgs) {\n super(args);\n this.numTokens = args.numTokens;\n\n if(args.outputMode) {\n this.outputMode = args.outputMode;\n } else {\n this.outputMode = 'multiHot';\n }\n }\n\n override getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'numTokens': this.numTokens,\n 'outputMode': this.outputMode,\n };\n\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n\n if(inputShape == null) {\n return [this.numTokens];\n }\n\n if(this.outputMode === 'oneHot' && inputShape[inputShape.length - 1] !== 1){\n inputShape.push(this.numTokens);\n return inputShape;\n }\n\n inputShape[inputShape.length - 1] = this.numTokens;\n return inputShape;\n }\n\n override call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor[]|Tensor {\n return tidy(() => {\n\n inputs = getExactlyOneTensor(inputs);\n if(inputs.dtype !== 'int32') {\n inputs = K.cast(inputs, 'int32');\n }\n\n let countWeights: Tensor1D | Tensor2D;\n\n if((typeof kwargs['countWeights']) !== 'undefined') {\n\n if(this.outputMode !== 'count') {\n throw new ValueError(\n `countWeights is not used when outputMode !== count.\n Received countWeights=${kwargs['countWeights']}`);\n }\n\n countWeights\n = getExactlyOneTensor(kwargs['countWeights']) as Tensor1D|Tensor2D;\n }\n\n const maxValue = max(inputs);\n const minValue = min(inputs);\n const greaterEqualMax = greater(this.numTokens, maxValue)\n .bufferSync().get(0);\n\n const greaterMin = greaterEqual(minValue, 0).bufferSync().get(0);\n\n if(!(greaterEqualMax && greaterMin)) {\n\n throw new ValueError('Input values must be between 0 < values <='\n + ` numTokens with numTokens=${this.numTokens}`);\n }\n\n return utils.encodeCategoricalInputs(inputs,\n this.outputMode, this.numTokens, countWeights);\n });\n }\n}\n\nserialization.registerClass(CategoryEncoding);\n","/**\n * @license\n * Copyright 2022 CodeSmith 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 { Tensor, denseBincount, Tensor1D, Tensor2D, TensorLike, mul} from '@tensorflow/tfjs-core';\nimport { getExactlyOneTensor } from '../../utils/types_utils';\nimport { expandDims} from '@tensorflow/tfjs-core';\nimport { ValueError } from '../../errors';\nimport * as K from '../../backend/tfjs_backend';\n\nexport type OutputMode = 'int' | 'oneHot' | 'multiHot' | 'count' | 'tfIdf';\n\nexport function encodeCategoricalInputs(inputs: Tensor|Tensor[],\n outputMode: OutputMode,\n depth: number,\n weights?: Tensor1D|Tensor2D|TensorLike):\n Tensor|Tensor[] {\n\n let input = getExactlyOneTensor(inputs);\n\n if(input.dtype !== 'int32') {\n input = K.cast(input, 'int32');\n }\n\n if(outputMode === 'int') {\n return input;\n }\n\n const originalShape = input.shape;\n\n if(input.rank === 0) {\n input = expandDims(input, -1);\n }\n\n if(outputMode === 'oneHot') {\n if(input.shape[input.shape.length - 1] !== 1) {\n input = expandDims(input, -1);\n }\n }\n\n if(input.rank > 2) {\n throw new ValueError(`When outputMode is not int, maximum output rank is 2`\n + ` Received outputMode ${outputMode} and input shape ${originalShape}`\n + ` which would result in output rank ${input.rank}.`);\n }\n\n const binaryOutput = ['multiHot', 'oneHot'].includes(outputMode);\n\n const denseBincountInput = input as Tensor1D | Tensor2D;\n\n let binCounts: Tensor1D | Tensor2D;\n\n if ((typeof weights) !== 'undefined' && outputMode === 'count') {\n binCounts = denseBincount(denseBincountInput, weights, depth, binaryOutput);\n } else {\n binCounts = denseBincount(denseBincountInput, [], depth, binaryOutput);\n }\n\n if(outputMode !== 'tfIdf') {\n return binCounts;\n }\n\n if (weights) {\n return mul(binCounts, weights);\n } else {\n throw new ValueError(\n `When outputMode is 'tfIdf', weights must be provided.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 CodeSmith 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 {image, Rank, serialization, Tensor, tidy} from '@tensorflow/tfjs-core'; // mul, add\n\nimport {Layer, LayerArgs} from '../../engine/topology';\nimport {ValueError} from '../../errors';\nimport {Shape} from '../../keras_format/common';\nimport {Kwargs} from '../../types';\nimport {getExactlyOneShape} from '../../utils/types_utils'; //, getExactlyOneTensor\n\n// tf methods unimplemented in tfjs: 'bicubic', 'area', 'lanczos3', 'lanczos5',\n// 'gaussian', 'mitchellcubic'\nconst INTERPOLATION_KEYS = ['bilinear', 'nearest'] as const;\nconst INTERPOLATION_METHODS = new Set(INTERPOLATION_KEYS);\ntype InterpolationType = typeof INTERPOLATION_KEYS[number];\n\nexport declare interface ResizingArgs extends LayerArgs {\n height: number;\n width: number;\n interpolation?: InterpolationType; // default = 'bilinear';\n cropToAspectRatio?: boolean; // default = false;\n}\n\n/**\n * Preprocessing Resizing Layer\n *\n * This resizes images by a scaling and offset factor\n */\n\nexport class Resizing extends Layer {\n /** @nocollapse */\n static className = 'Resizing';\n private readonly height: number;\n private readonly width: number;\n // method of interpolation to be used; default = \"bilinear\";\n private readonly interpolation: InterpolationType;\n // toggle whether the aspect ratio should be preserved; default = false;\n private readonly cropToAspectRatio: boolean;\n\n constructor(args: ResizingArgs) {\n super(args);\n\n this.height = args.height;\n this.width = args.width;\n\n if (args.interpolation) {\n if (INTERPOLATION_METHODS.has(args.interpolation)) {\n this.interpolation = args.interpolation;\n } else {\n throw new ValueError(`Invalid interpolation parameter: ${\n args.interpolation} is not implemented`);\n }\n } else {\n this.interpolation = 'bilinear';\n }\n this.cropToAspectRatio = Boolean(args.cropToAspectRatio);\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const numChannels = inputShape[2];\n return [this.height, this.width, numChannels];\n }\n\n override getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'height': this.height,\n 'width': this.width,\n 'interpolation': this.interpolation,\n 'cropToAspectRatio': this.cropToAspectRatio\n };\n\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n override call(inputs: Tensor|Tensor, kwargs: Kwargs):\n Tensor[]|Tensor {\n return tidy(() => {\n const size: [number, number] = [this.height, this.width];\n if (this.interpolation === 'bilinear') {\n return image.resizeBilinear(inputs, size, !this.cropToAspectRatio);\n } else if (this.interpolation === 'nearest') {\n return image.resizeNearestNeighbor(\n inputs, size, !this.cropToAspectRatio);\n } else {\n throw new Error(`Interpolation is ${this.interpolation} but only ${[...INTERPOLATION_METHODS]} are supported`);\n }\n });\n }\n}\n\nserialization.registerClass(Resizing);\n","/**\n * @license\n * Copyright 2023 CodeSmith 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 * Keeps track of seed and handles pseudorandomness\n * Instance created in BaseRandomLayer class\n * Utilized for random preprocessing layers\n */\n\nexport class RandomSeed {\n static className = 'RandomSeed';\n seed: number | undefined;\n constructor(seed: number | undefined) { \n this.seed = seed; \n }\n next(): number | undefined { \n if (this.seed === undefined) {\n return undefined;\n }\n return this.seed++; \n }\n}\n","/**\n * @license\n * Copyright 2023 CodeSmith 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 { LayerArgs, Layer } from './topology';\nimport { RandomSeed } from '../backend/random_seed';\nimport { serialization } from '@tensorflow/tfjs-core';\n\nexport declare interface BaseRandomLayerArgs extends LayerArgs {\n seed?: number;\n}\n\nexport abstract class BaseRandomLayer extends Layer {\n // A layer handle the random number creation and savemodel behavior.\n /** @nocollapse */\n static className = 'BaseRandomLayer';\n protected randomGenerator: RandomSeed;\n\n constructor(args: BaseRandomLayerArgs) {\n super(args);\n this.randomGenerator = new RandomSeed(args.seed);\n }\n\n override getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'seed': this.randomGenerator.seed\n };\n\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\n","/**\n * @license\n * Copyright 2023 CodeSmith 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 { image, Rank, serialization, Tensor, tidy } from '@tensorflow/tfjs-core';\nimport { getExactlyOneTensor, getExactlyOneShape } from '../../utils/types_utils';\nimport { Shape } from '../../keras_format/common';\nimport { Kwargs } from '../../types';\nimport { ValueError } from '../../errors';\nimport { BaseRandomLayerArgs, BaseRandomLayer } from '../../engine/base_random_layer';\nimport { randomUniform } from '@tensorflow/tfjs-core';\n\nexport declare interface RandomWidthArgs extends BaseRandomLayerArgs {\n factor: number | [number, number];\n interpolation?: InterpolationType; // default = 'bilinear';\n seed?: number; // default = null;\n autoVectorize?: boolean;\n}\n\nconst INTERPOLATION_KEYS = ['bilinear', 'nearest'] as const;\nexport const INTERPOLATION_METHODS = new Set(INTERPOLATION_KEYS);\ntype InterpolationType = typeof INTERPOLATION_KEYS[number];\n\n/**\n * Preprocessing Layer with randomly varies image during training\n *\n * This layer randomly adjusts the width of a batch of images of a\n * batch of images by a random factor.\n *\n * The input should be a 3D (unbatched) or\n * 4D (batched) tensor in the `\"channels_last\"` image data format. Input pixel\n * values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and of interger\n * or floating point dtype. By default, the layer will output floats.\n *\n * tf methods implemented in tfjs: 'bilinear', 'nearest',\n * tf methods unimplemented in tfjs: 'bicubic', 'area', 'lanczos3', 'lanczos5',\n * 'gaussian', 'mitchellcubic'\n *\n */\n\nexport class RandomWidth extends BaseRandomLayer {\n /** @nocollapse */\n static override className = 'RandomWidth';\n private readonly factor: number | [number, number];\n private readonly interpolation?: InterpolationType; // defualt = 'bilinear\n private widthLower: number;\n private widthUpper: number;\n private imgHeight: number;\n private widthFactor: Tensor;\n\n constructor(args: RandomWidthArgs) {\n super(args);\n const {factor, interpolation = 'bilinear'} = args;\n\n this.factor = factor;\n\n if (Array.isArray(this.factor) && this.factor.length === 2) {\n this.widthLower = this.factor[0];\n this.widthUpper = this.factor[1];\n } else if (!Array.isArray(this.factor) && this.factor > 0){\n this.widthLower = -this.factor;\n this.widthUpper = this.factor;\n } else {\n throw new ValueError(\n `Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`\n );\n }\n if (this.widthLower < -1.0 || this.widthUpper < -1.0) {\n throw new ValueError(\n `factor must have values larger than -1. Got: ${this.factor}`\n );\n }\n\n if (this.widthUpper < this.widthLower) {\n throw new ValueError(\n `factor cannot have upper bound less than lower bound.\n Got upper bound: ${this.widthUpper}.\n Got lower bound: ${this.widthLower}\n `);\n }\n\n if (interpolation) {\n if (INTERPOLATION_METHODS.has(interpolation)) {\n this.interpolation = interpolation;\n } else {\n throw new ValueError(`Invalid interpolation parameter: ${\n interpolation} is not implemented`);\n }\n } \n }\n\n override getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'factor': this.factor,\n 'interpolation': this.interpolation,\n };\n\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n override computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const numChannels = inputShape[2];\n return [this.imgHeight, -1, numChannels];\n }\n\n override call(inputs: Tensor|Tensor,\n kwargs: Kwargs): Tensor[]|Tensor {\n\n return tidy(() => {\n const input = getExactlyOneTensor(inputs);\n this.imgHeight = input.shape[input.shape.length - 3];\n const imgWidth = input.shape[input.shape.length - 2];\n\n this.widthFactor = randomUniform([1],\n (1.0 + this.widthLower), (1.0 + this.widthUpper),\n 'float32', this.randomGenerator.next()\n );\n\n let adjustedWidth = this.widthFactor.dataSync()[0] * imgWidth;\n adjustedWidth = Math.round(adjustedWidth);\n\n const size:[number, number] = [this.imgHeight, adjustedWidth];\n\n switch (this.interpolation) {\n case 'bilinear':\n return image.resizeBilinear(inputs, size);\n case 'nearest':\n return image.resizeNearestNeighbor(inputs, size);\n default:\n throw new Error(`Interpolation is ${this.interpolation}\n but only ${[...INTERPOLATION_METHODS]} are supported`);\n }\n });\n }\n}\n\nserialization.registerClass(RandomWidth);\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {InputLayer, InputLayerArgs} from './engine/input_layer';\nimport {Layer, LayerArgs} from './engine/topology';\nimport {input} from './exports';\nimport {ELU, ELULayerArgs, LeakyReLU, LeakyReLULayerArgs, PReLU, PReLULayerArgs, ReLU, ReLULayerArgs, Softmax, SoftmaxLayerArgs, ThresholdedReLU, ThresholdedReLULayerArgs} from './layers/advanced_activations';\nimport {Conv1D, Conv2D, Conv2DTranspose, Conv3D, ConvLayerArgs, Cropping2D, Cropping2DLayerArgs, SeparableConv2D, SeparableConvLayerArgs, UpSampling2D, UpSampling2DLayerArgs, Conv3DTranspose} from './layers/convolutional';\nimport {DepthwiseConv2D, DepthwiseConv2DLayerArgs} from './layers/convolutional_depthwise';\nimport {ConvLSTM2D, ConvLSTM2DArgs, ConvLSTM2DCell, ConvLSTM2DCellArgs} from './layers/convolutional_recurrent';\nimport {Activation, ActivationLayerArgs, Dense, DenseLayerArgs, Dropout, DropoutLayerArgs, Flatten, FlattenLayerArgs, Masking, MaskingArgs, Permute, PermuteLayerArgs, RepeatVector, RepeatVectorLayerArgs, Reshape, ReshapeLayerArgs, SpatialDropout1D, SpatialDropout1DLayerConfig} from './layers/core';\nimport {Embedding, EmbeddingLayerArgs} from './layers/embeddings';\nimport {Add, Average, Concatenate, ConcatenateLayerArgs, Dot, DotLayerArgs, Maximum, Minimum, Multiply} from './layers/merge';\nimport {AlphaDropout, AlphaDropoutArgs, GaussianDropout, GaussianDropoutArgs, GaussianNoise, GaussianNoiseArgs} from './layers/noise';\nimport {BatchNormalization, BatchNormalizationLayerArgs, LayerNormalization, LayerNormalizationLayerArgs} from './layers/normalization';\nimport {ZeroPadding2D, ZeroPadding2DLayerArgs} from './layers/padding';\nimport {AveragePooling1D, AveragePooling2D, AveragePooling3D, GlobalAveragePooling1D, GlobalAveragePooling2D, GlobalMaxPooling1D, GlobalMaxPooling2D, GlobalPooling2DLayerArgs, MaxPooling1D, MaxPooling2D, MaxPooling3D, Pooling1DLayerArgs, Pooling2DLayerArgs, Pooling3DLayerArgs} from './layers/pooling';\nimport {GRU, GRUCell, GRUCellLayerArgs, GRULayerArgs, LSTM, LSTMCell, LSTMCellLayerArgs, LSTMLayerArgs, RNN, RNNCell, RNNLayerArgs, SimpleRNN, SimpleRNNCell, SimpleRNNCellLayerArgs, SimpleRNNLayerArgs, StackedRNNCells, StackedRNNCellsArgs} from './layers/recurrent';\nimport {Bidirectional, BidirectionalLayerArgs, TimeDistributed, WrapperLayerArgs} from './layers/wrappers';\nimport {Rescaling, RescalingArgs} from './layers/preprocessing/image_preprocessing';\nimport {CenterCrop, CenterCropArgs} from './layers/preprocessing/center_crop';\nimport {CategoryEncoding, CategoryEncodingArgs} from './layers/preprocessing/category_encoding';\nimport {Resizing, ResizingArgs} from './layers/preprocessing/image_resizing';\nimport {RandomWidth, RandomWidthArgs} from './layers/preprocessing/random_width';\n\n// TODO(cais): Add doc string to all the public static functions in this\n// class; include exectuable JavaScript code snippets where applicable\n// (b/74074458).\n\n// Input Layer.\n/**\n * An input layer is an entry point into a `tf.LayersModel`.\n *\n * `InputLayer` is generated automatically for `tf.Sequential` models by\n * specifying the `inputshape` or `batchInputShape` for the first layer. It\n * should not be specified explicitly. However, it can be useful sometimes,\n * e.g., when constructing a sequential model from a subset of another\n * sequential model's layers. Like the code snippet below shows.\n *\n * ```js\n * // Define a model which simply adds two inputs.\n * const model1 = tf.sequential();\n * model1.add(tf.layers.dense({inputShape: [4], units: 3, activation: 'relu'}));\n * model1.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));\n * model1.summary();\n * model1.predict(tf.zeros([1, 4])).print();\n *\n * // Construct another model, reusing the second layer of `model1` while\n * // not using the first layer of `model1`. Note that you cannot add the second\n * // layer of `model` directly as the first layer of the new sequential model,\n * // because doing so will lead to an error related to the fact that the layer\n * // is not an input layer. Instead, you need to create an `inputLayer` and add\n * // it to the new sequential model before adding the reused layer.\n * const model2 = tf.sequential();\n * // Use an inputShape that matches the input shape of `model1`'s second\n * // layer.\n * model2.add(tf.layers.inputLayer({inputShape: [3]}));\n * model2.add(model1.layers[1]);\n * model2.summary();\n * model2.predict(tf.zeros([1, 3])).print();\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Inputs', namespace: 'layers'}\n */\nexport function inputLayer(args: InputLayerArgs) {\n return new InputLayer(args);\n}\n\n// Advanced Activation Layers.\n\n/**\n * Exponential Linear Unit (ELU).\n *\n * It follows:\n * `f(x) = alpha * (exp(x) - 1.) for x < 0`,\n * `f(x) = x for x >= 0`.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * References:\n * - [Fast and Accurate Deep Network Learning by Exponential Linear Units\n * (ELUs)](https://arxiv.org/abs/1511.07289v1)\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function elu(args?: ELULayerArgs) {\n return new ELU(args);\n}\n\n/**\n * Rectified Linear Unit activation function.\n *\n * Input shape:\n * Arbitrary. Use the config field `inputShape` (Array of integers, does\n * not include the sample axis) when using this layer as the first layer\n * in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function reLU(args?: ReLULayerArgs) {\n return new ReLU(args);\n}\n\n/**\n * Leaky version of a rectified linear unit.\n *\n * It allows a small gradient when the unit is not active:\n * `f(x) = alpha * x for x < 0.`\n * `f(x) = x for x >= 0.`\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function leakyReLU(args?: LeakyReLULayerArgs) {\n return new LeakyReLU(args);\n}\n\n/**\n * Parameterized version of a leaky rectified linear unit.\n *\n * It follows\n * `f(x) = alpha * x for x < 0.`\n * `f(x) = x for x >= 0.`\n * wherein `alpha` is a trainable weight.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function prelu(args?: PReLULayerArgs) {\n return new PReLU(args);\n}\n\n/**\n * Softmax activation layer.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function softmax(args?: SoftmaxLayerArgs) {\n return new Softmax(args);\n}\n\n/**\n * Thresholded Rectified Linear Unit.\n *\n * It follows:\n * `f(x) = x for x > theta`,\n * `f(x) = 0 otherwise`.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * References:\n * - [Zero-Bias Autoencoders and the Benefits of Co-Adapting\n * Features](http://arxiv.org/abs/1402.3337)\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function thresholdedReLU(args?: ThresholdedReLULayerArgs) {\n return new ThresholdedReLU(args);\n}\n\n// Convolutional Layers.\n\n/**\n * 1D convolution layer (e.g., temporal convolution).\n *\n * This layer creates a convolution kernel that is convolved\n * with the layer input over a single spatial (or temporal) dimension\n * to produce a tensor of outputs.\n *\n * If `use_bias` is True, a bias vector is created and added to the outputs.\n *\n * If `activation` is not `null`, it is applied to the outputs as well.\n *\n * When using this layer as the first layer in a model, provide an\n * `inputShape` argument `Array` or `null`.\n *\n * For example, `inputShape` would be:\n * - `[10, 128]` for sequences of 10 vectors of 128-dimensional vectors\n * - `[null, 128]` for variable-length sequences of 128-dimensional vectors.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv1d(args: ConvLayerArgs) {\n return new Conv1D(args);\n}\n\n/**\n * 2D convolution layer (e.g. spatial convolution over images).\n *\n * This layer creates a convolution kernel that is convolved\n * with the layer input to produce a tensor of outputs.\n *\n * If `useBias` is True, a bias vector is created and added to the outputs.\n *\n * If `activation` is not `null`, it is applied to the outputs as well.\n *\n * When using this layer as the first layer in a model,\n * provide the keyword argument `inputShape`\n * (Array of integers, does not include the sample axis),\n * e.g. `inputShape=[128, 128, 3]` for 128x128 RGB pictures\n * in `dataFormat='channelsLast'`.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv2d(args: ConvLayerArgs) {\n return new Conv2D(args);\n}\n\n/**\n * Transposed convolutional layer (sometimes called Deconvolution).\n *\n * The need for transposed convolutions generally arises\n * from the desire to use a transformation going in the opposite direction of\n * a normal convolution, i.e., from something that has the shape of the output\n * of some convolution to something that has the shape of its input while\n * maintaining a connectivity pattern that is compatible with said\n * convolution.\n *\n * When using this layer as the first layer in a model, provide the\n * configuration `inputShape` (`Array` of integers, does not include the\n * sample axis), e.g., `inputShape: [128, 128, 3]` for 128x128 RGB pictures in\n * `dataFormat: 'channelsLast'`.\n *\n * Input shape:\n * 4D tensor with shape:\n * `[batch, channels, rows, cols]` if `dataFormat` is `'channelsFirst'`.\n * or 4D tensor with shape\n * `[batch, rows, cols, channels]` if `dataFormat` is `'channelsLast'`.\n *\n * Output shape:\n * 4D tensor with shape:\n * `[batch, filters, newRows, newCols]` if `dataFormat` is\n * `'channelsFirst'`. or 4D tensor with shape:\n * `[batch, newRows, newCols, filters]` if `dataFormat` is `'channelsLast'`.\n *\n * References:\n * - [A guide to convolution arithmetic for deep\n * learning](https://arxiv.org/abs/1603.07285v1)\n * - [Deconvolutional\n * Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf)\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv2dTranspose(args: ConvLayerArgs) {\n return new Conv2DTranspose(args);\n}\n\n/**\n * 3D convolution layer (e.g. spatial convolution over volumes).\n *\n * This layer creates a convolution kernel that is convolved\n * with the layer input to produce a tensor of outputs.\n *\n * If `useBias` is True, a bias vector is created and added to the outputs.\n *\n * If `activation` is not `null`, it is applied to the outputs as well.\n *\n * When using this layer as the first layer in a model,\n * provide the keyword argument `inputShape`\n * (Array of integers, does not include the sample axis),\n * e.g. `inputShape=[128, 128, 128, 1]` for 128x128x128 grayscale volumes\n * in `dataFormat='channelsLast'`.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv3d(args: ConvLayerArgs) {\n return new Conv3D(args);\n}\n\nexport function conv3dTranspose(args: ConvLayerArgs): Layer {\n return new Conv3DTranspose(args);\n}\n\n/**\n * Depthwise separable 2D convolution.\n *\n * Separable convolution consists of first performing\n * a depthwise spatial convolution\n * (which acts on each input channel separately)\n * followed by a pointwise convolution which mixes together the resulting\n * output channels. The `depthMultiplier` argument controls how many\n * output channels are generated per input channel in the depthwise step.\n *\n * Intuitively, separable convolutions can be understood as\n * a way to factorize a convolution kernel into two smaller kernels,\n * or as an extreme version of an Inception block.\n *\n * Input shape:\n * 4D tensor with shape:\n * `[batch, channels, rows, cols]` if data_format='channelsFirst'\n * or 4D tensor with shape:\n * `[batch, rows, cols, channels]` if data_format='channelsLast'.\n *\n * Output shape:\n * 4D tensor with shape:\n * `[batch, filters, newRows, newCols]` if data_format='channelsFirst'\n * or 4D tensor with shape:\n * `[batch, newRows, newCols, filters]` if data_format='channelsLast'.\n * `rows` and `cols` values might have changed due to padding.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function separableConv2d(args: SeparableConvLayerArgs) {\n return new SeparableConv2D(args);\n}\n\n/**\n * Cropping layer for 2D input (e.g., image).\n *\n * This layer can crop an input\n * at the top, bottom, left and right side of an image tensor.\n *\n * Input shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, rows, cols, channels]`\n * - If `data_format` is `\"channels_first\"`:\n * `[batch, channels, rows, cols]`.\n *\n * Output shape:\n * 4D with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, croppedRows, croppedCols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, croppedRows, croppedCols]`.\n *\n * Examples\n * ```js\n *\n * const model = tf.sequential();\n * model.add(tf.layers.cropping2D({cropping:[[2, 2], [2, 2]],\n * inputShape: [128, 128, 3]}));\n * //now output shape is [batch, 124, 124, 3]\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function cropping2D(args: Cropping2DLayerArgs) {\n return new Cropping2D(args);\n}\n\n/**\n * Upsampling layer for 2D inputs.\n *\n * Repeats the rows and columns of the data\n * by size[0] and size[1] respectively.\n *\n *\n * Input shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, rows, cols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, rows, cols]`\n *\n * Output shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, upsampledRows, upsampledCols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, upsampledRows, upsampledCols]`\n *\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function upSampling2d(args: UpSampling2DLayerArgs) {\n return new UpSampling2D(args);\n}\n\n// Convolutional(depthwise) Layers.\n\n/**\n * Depthwise separable 2D convolution.\n *\n * Depthwise Separable convolutions consists in performing just the first step\n * in a depthwise spatial convolution (which acts on each input channel\n * separately). The `depthMultiplier` argument controls how many output channels\n * are generated per input channel in the depthwise step.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function depthwiseConv2d(args: DepthwiseConv2DLayerArgs) {\n return new DepthwiseConv2D(args);\n}\n\n// Basic Layers.\n\n/**\n * Applies an activation function to an output.\n *\n * This layer applies element-wise activation function. Other layers, notably\n * `dense` can also apply activation functions. Use this isolated activation\n * function to extract the values before and after the\n * activation. For instance:\n *\n * ```js\n * const input = tf.input({shape: [5]});\n * const denseLayer = tf.layers.dense({units: 1});\n * const activationLayer = tf.layers.activation({activation: 'relu6'});\n *\n * // Obtain the output symbolic tensors by applying the layers in order.\n * const denseOutput = denseLayer.apply(input);\n * const activationOutput = activationLayer.apply(denseOutput);\n *\n * // Create the model based on the inputs.\n * const model = tf.model({\n * inputs: input,\n * outputs: [denseOutput, activationOutput]\n * });\n *\n * // Collect both outputs and print separately.\n * const [denseOut, activationOut] = model.predict(tf.randomNormal([6, 5]));\n * denseOut.print();\n * activationOut.print();\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function activation(args: ActivationLayerArgs) {\n return new Activation(args);\n}\n\n/**\n * Creates a dense (fully connected) layer.\n *\n * This layer implements the operation:\n * `output = activation(dot(input, kernel) + bias)`\n *\n * `activation` is the element-wise activation function\n * passed as the `activation` argument.\n *\n * `kernel` is a weights matrix created by the layer.\n *\n * `bias` is a bias vector created by the layer (only applicable if `useBias`\n * is `true`).\n *\n * **Input shape:**\n *\n * nD `tf.Tensor` with shape: `(batchSize, ..., inputDim)`.\n *\n * The most common situation would be\n * a 2D input with shape `(batchSize, inputDim)`.\n *\n * **Output shape:**\n *\n * nD tensor with shape: `(batchSize, ..., units)`.\n *\n * For instance, for a 2D input with shape `(batchSize, inputDim)`,\n * the output would have shape `(batchSize, units)`.\n *\n * Note: if the input to the layer has a rank greater than 2, then it is\n * flattened prior to the initial dot product with the kernel.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function dense(args: DenseLayerArgs) {\n return new Dense(args);\n}\n\n/**\n * Applies\n * [dropout](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) to\n * the input.\n *\n * Dropout consists in randomly setting a fraction `rate` of input units to 0 at\n * each update during training time, which helps prevent overfitting.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function dropout(args: DropoutLayerArgs) {\n return new Dropout(args);\n}\n\n/**\n * Spatial 1D version of Dropout.\n *\n * This Layer type performs the same function as the Dropout layer, but it drops\n * entire 1D feature maps instead of individual elements. For example, if an\n * input example consists of 3 timesteps and the feature map for each timestep\n * has a size of 4, a `spatialDropout1d` layer may zero out the feature maps\n * of the 1st timesteps and 2nd timesteps completely while sparing all feature\n * elements of the 3rd timestep.\n *\n * If adjacent frames (timesteps) are strongly correlated (as is normally the\n * case in early convolution layers), regular dropout will not regularize the\n * activation and will otherwise just result in merely an effective learning\n * rate decrease. In this case, `spatialDropout1d` will help promote\n * independence among feature maps and should be used instead.\n *\n * **Arguments:**\n * rate: A floating-point number >=0 and <=1. Fraction of the input elements\n * to drop.\n *\n * **Input shape:**\n * 3D tensor with shape `(samples, timesteps, channels)`.\n *\n * **Output shape:**\n * Same as the input shape.\n *\n * References:\n * - [Efficient Object Localization Using Convolutional\n * Networks](https://arxiv.org/abs/1411.4280)\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function spatialDropout1d(args: SpatialDropout1DLayerConfig) {\n return new SpatialDropout1D(args);\n}\n\n/**\n * Flattens the input. Does not affect the batch size.\n *\n * A `Flatten` layer flattens each batch in its inputs to 1D (making the output\n * 2D).\n *\n * For example:\n *\n * ```js\n * const input = tf.input({shape: [4, 3]});\n * const flattenLayer = tf.layers.flatten();\n * // Inspect the inferred output shape of the flatten layer, which\n * // equals `[null, 12]`. The 2nd dimension is 4 * 3, i.e., the result of the\n * // flattening. (The 1st dimension is the undermined batch size.)\n * console.log(JSON.stringify(flattenLayer.apply(input).shape));\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function flatten(args?: FlattenLayerArgs) {\n return new Flatten(args);\n}\n\n/**\n * Repeats the input n times in a new dimension.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.repeatVector({n: 4, inputShape: [2]}));\n * const x = tf.tensor2d([[10, 20]]);\n * // Use the model to do inference on a data point the model hasn't seen\n * model.predict(x).print();\n * // output shape is now [batch, 2, 4]\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function repeatVector(args: RepeatVectorLayerArgs) {\n return new RepeatVector(args);\n}\n\n/**\n * Reshapes an input to a certain shape.\n *\n * ```js\n * const input = tf.input({shape: [4, 3]});\n * const reshapeLayer = tf.layers.reshape({targetShape: [2, 6]});\n * // Inspect the inferred output shape of the Reshape layer, which\n * // equals `[null, 2, 6]`. (The 1st dimension is the undermined batch size.)\n * console.log(JSON.stringify(reshapeLayer.apply(input).shape));\n * ```\n *\n * Input shape:\n * Arbitrary, although all dimensions in the input shape must be fixed.\n * Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n *\n * Output shape:\n * [batchSize, targetShape[0], targetShape[1], ...,\n * targetShape[targetShape.length - 1]].\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function reshape(args: ReshapeLayerArgs) {\n return new Reshape(args);\n}\n\n/**\n * Permutes the dimensions of the input according to a given pattern.\n *\n * Useful for, e.g., connecting RNNs and convnets together.\n *\n * Example:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.permute({\n * dims: [2, 1],\n * inputShape: [10, 64]\n * }));\n * console.log(model.outputShape);\n * // Now model's output shape is [null, 64, 10], where null is the\n * // unpermuted sample (batch) dimension.\n * ```\n *\n * Input shape:\n * Arbitrary. Use the configuration field `inputShape` when using this\n * layer as the first layer in a model.\n *\n * Output shape:\n * Same rank as the input shape, but with the dimensions re-ordered (i.e.,\n * permuted) according to the `dims` configuration of this layer.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function permute(args: PermuteLayerArgs) {\n return new Permute(args);\n}\n\n/**\n * Maps positive integers (indices) into dense vectors of fixed size.\n * E.g. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n *\n * **Input shape:** 2D tensor with shape: `[batchSize, sequenceLength]`.\n *\n * **Output shape:** 3D tensor with shape: `[batchSize, sequenceLength,\n * outputDim]`.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function embedding(args: EmbeddingLayerArgs) {\n return new Embedding(args);\n}\n\n// Merge Layers.\n\n/**\n * Layer that performs element-wise addition on an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape, and returns a\n * single tensor (also of the same shape). The inputs are specified as an\n * `Array` when the `apply` method of the `Add` layer instance is called. For\n * example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const addLayer = tf.layers.add();\n * const sum = addLayer.apply([input1, input2]);\n * console.log(JSON.stringify(sum.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function add(args?: LayerArgs) {\n return new Add(args);\n}\n\n/**\n * Layer that performs element-wise averaging on an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape, and returns a\n * single tensor (also of the same shape). For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const averageLayer = tf.layers.average();\n * const average = averageLayer.apply([input1, input2]);\n * console.log(JSON.stringify(average.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function average(args?: LayerArgs) {\n return new Average(args);\n}\n\n/**\n * Layer that concatenates an `Array` of inputs.\n *\n * It takes a list of tensors, all of the same shape except for the\n * concatenation axis, and returns a single tensor, the concatenation\n * of all inputs. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 3]});\n * const concatLayer = tf.layers.concatenate();\n * const output = concatLayer.apply([input1, input2]);\n * console.log(JSON.stringify(output.shape));\n * // You get [null, 2, 5], with the first dimension as the undetermined batch\n * // dimension. The last dimension (5) is the result of concatenating the\n * // last dimensions of the inputs (2 and 3).\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function concatenate(args?: ConcatenateLayerArgs) {\n return new Concatenate(args);\n}\n\n/**\n * Layer that computes the element-wise maximum of an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape, and returns a\n * single tensor (also of the same shape). For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const maxLayer = tf.layers.maximum();\n * const max = maxLayer.apply([input1, input2]);\n * console.log(JSON.stringify(max.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function maximum(args?: LayerArgs) {\n return new Maximum(args);\n}\n\n/**\n * Layer that computes the element-wise minimum of an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape, and returns a\n * single tensor (also of the same shape). For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const minLayer = tf.layers.minimum();\n * const min = minLayer.apply([input1, input2]);\n * console.log(JSON.stringify(min.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function minimum(args?: LayerArgs) {\n return new Minimum(args);\n}\n\n/**\n * Layer that multiplies (element-wise) an `Array` of inputs.\n *\n * It takes as input an Array of tensors, all of the same\n * shape, and returns a single tensor (also of the same shape).\n * For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const input3 = tf.input({shape: [2, 2]});\n * const multiplyLayer = tf.layers.multiply();\n * const product = multiplyLayer.apply([input1, input2, input3]);\n * console.log(product.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function multiply(args?: LayerArgs) {\n return new Multiply(args);\n}\n\n/**\n * Layer that computes a dot product between samples in two tensors.\n *\n * E.g., if applied to a list of two tensors `a` and `b` both of shape\n * `[batchSize, n]`, the output will be a tensor of shape `[batchSize, 1]`,\n * where each entry at index `[i, 0]` will be the dot product between\n * `a[i, :]` and `b[i, :]`.\n *\n * Example:\n *\n * ```js\n * const dotLayer = tf.layers.dot({axes: -1});\n * const x1 = tf.tensor2d([[10, 20], [30, 40]]);\n * const x2 = tf.tensor2d([[-1, -2], [-3, -4]]);\n *\n * // Invoke the layer's apply() method in eager (imperative) mode.\n * const y = dotLayer.apply([x1, x2]);\n * y.print();\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function dot(args: DotLayerArgs) {\n return new Dot(args);\n}\n\n// Normalization Layers.\n\n/**\n * Batch normalization layer (Ioffe and Szegedy, 2014).\n *\n * Normalize the activations of the previous layer at each batch,\n * i.e. applies a transformation that maintains the mean activation\n * close to 0 and the activation standard deviation close to 1.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape` (Array of integers, does\n * not include the sample axis) when calling the constructor of this class,\n * if this layer is used as a first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Batch Normalization: Accelerating Deep Network Training by Reducing\n * Internal Covariate Shift](https://arxiv.org/abs/1502.03167)\n *\n * @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}\n */\nexport function batchNormalization(args?: BatchNormalizationLayerArgs) {\n return new BatchNormalization(args);\n}\n\n/**\n * Layer-normalization layer (Ba et al., 2016).\n *\n * Normalizes the activations of the previous layer for each given example in a\n * batch independently, instead of across a batch like in `batchNormalization`.\n * In other words, this layer applies a transformation that maintains the mean\n * activation within each example close to 0 and activation variance close to 1.\n *\n * Input shape:\n * Arbitrary. Use the argument `inputShape` when using this layer as the first\n * layer in a model.\n *\n * Output shape:\n * Same as input.\n *\n * References:\n * - [Layer Normalization](https://arxiv.org/abs/1607.06450)\n *\n * @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}\n */\nexport function layerNormalization(args?: LayerNormalizationLayerArgs) {\n return new LayerNormalization(args);\n}\n\n// Padding Layers.\n\n/**\n * Zero-padding layer for 2D input (e.g., image).\n *\n * This layer can add rows and columns of zeros\n * at the top, bottom, left and right side of an image tensor.\n *\n * Input shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, rows, cols, channels]`\n * - If `data_format` is `\"channels_first\"`:\n * `[batch, channels, rows, cols]`.\n *\n * Output shape:\n * 4D with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, paddedRows, paddedCols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, paddedRows, paddedCols]`.\n *\n * @doc {heading: 'Layers', subheading: 'Padding', namespace: 'layers'}\n */\nexport function zeroPadding2d(args?: ZeroPadding2DLayerArgs) {\n return new ZeroPadding2D(args);\n}\n\n// Pooling Layers.\n\n/**\n * Average pooling operation for spatial data.\n *\n * Input shape: `[batchSize, inLength, channels]`\n *\n * Output shape: `[batchSize, pooledLength, channels]`\n *\n * `tf.avgPool1d` is an alias.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function averagePooling1d(args: Pooling1DLayerArgs) {\n return new AveragePooling1D(args);\n}\nexport function avgPool1d(args: Pooling1DLayerArgs) {\n return averagePooling1d(args);\n}\n// For backwards compatibility.\n// See https://github.com/tensorflow/tfjs/issues/152\nexport function avgPooling1d(args: Pooling1DLayerArgs) {\n return averagePooling1d(args);\n}\n\n/**\n * Average pooling operation for spatial data.\n *\n * Input shape:\n * - If `dataFormat === CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, rows, cols, channels]`\n * - If `dataFormat === CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, rows, cols]`\n *\n * Output shape\n * - If `dataFormat === CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, pooledRows, pooledCols, channels]`\n * - If `dataFormat === CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, pooledRows, pooledCols]`\n *\n * `tf.avgPool2d` is an alias.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function averagePooling2d(args: Pooling2DLayerArgs) {\n return new AveragePooling2D(args);\n}\nexport function avgPool2d(args: Pooling2DLayerArgs) {\n return averagePooling2d(args);\n}\n// For backwards compatibility.\n// See https://github.com/tensorflow/tfjs/issues/152\nexport function avgPooling2d(args: Pooling2DLayerArgs) {\n return averagePooling2d(args);\n}\n\n/**\n * Average pooling operation for 3D data.\n *\n * Input shape\n * - If `dataFormat === channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, depths, rows, cols, channels]`\n * - If `dataFormat === channelsFirst`:\n * 4D tensor with shape:\n * `[batchSize, channels, depths, rows, cols]`\n *\n * Output shape\n * - If `dataFormat=channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, pooledDepths, pooledRows, pooledCols, channels]`\n * - If `dataFormat=channelsFirst`:\n * 5D tensor with shape:\n * `[batchSize, channels, pooledDepths, pooledRows, pooledCols]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function averagePooling3d(args: Pooling3DLayerArgs) {\n return new AveragePooling3D(args);\n}\nexport function avgPool3d(args: Pooling3DLayerArgs) {\n return averagePooling3d(args);\n}\n// For backwards compatibility.\n// See https://github.com/tensorflow/tfjs/issues/152\nexport function avgPooling3d(args: Pooling3DLayerArgs) {\n return averagePooling3d(args);\n}\n\n/**\n * Global average pooling operation for temporal data.\n *\n * Input Shape: 3D tensor with shape: `[batchSize, steps, features]`.\n *\n * Output Shape: 2D tensor with shape: `[batchSize, features]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalAveragePooling1d(args?: LayerArgs) {\n return new GlobalAveragePooling1D(args);\n}\n\n/**\n * Global average pooling operation for spatial data.\n *\n * Input shape:\n * - If `dataFormat` is `CHANNEL_LAST`:\n * 4D tensor with shape: `[batchSize, rows, cols, channels]`.\n * - If `dataFormat` is `CHANNEL_FIRST`:\n * 4D tensor with shape: `[batchSize, channels, rows, cols]`.\n *\n * Output shape:\n * 2D tensor with shape: `[batchSize, channels]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalAveragePooling2d(args: GlobalPooling2DLayerArgs) {\n return new GlobalAveragePooling2D(args);\n}\n\n/**\n * Global max pooling operation for temporal data.\n *\n * Input Shape: 3D tensor with shape: `[batchSize, steps, features]`.\n *\n * Output Shape: 2D tensor with shape: `[batchSize, features]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalMaxPooling1d(args?: LayerArgs) {\n return new GlobalMaxPooling1D(args);\n}\n\n/**\n * Global max pooling operation for spatial data.\n *\n * Input shape:\n * - If `dataFormat` is `CHANNEL_LAST`:\n * 4D tensor with shape: `[batchSize, rows, cols, channels]`.\n * - If `dataFormat` is `CHANNEL_FIRST`:\n * 4D tensor with shape: `[batchSize, channels, rows, cols]`.\n *\n * Output shape:\n * 2D tensor with shape: `[batchSize, channels]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalMaxPooling2d(args: GlobalPooling2DLayerArgs) {\n return new GlobalMaxPooling2D(args);\n}\n\n/**\n * Max pooling operation for temporal data.\n *\n * Input shape: `[batchSize, inLength, channels]`\n *\n * Output shape: `[batchSize, pooledLength, channels]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function maxPooling1d(args: Pooling1DLayerArgs) {\n return new MaxPooling1D(args);\n}\n\n/**\n * Max pooling operation for spatial data.\n *\n * Input shape\n * - If `dataFormat === CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, rows, cols, channels]`\n * - If `dataFormat === CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, rows, cols]`\n *\n * Output shape\n * - If `dataFormat=CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, pooledRows, pooledCols, channels]`\n * - If `dataFormat=CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, pooledRows, pooledCols]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function maxPooling2d(args: Pooling2DLayerArgs) {\n return new MaxPooling2D(args);\n}\n\n/**\n * Max pooling operation for 3D data.\n *\n * Input shape\n * - If `dataFormat === channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, depths, rows, cols, channels]`\n * - If `dataFormat === channelsFirst`:\n * 5D tensor with shape:\n * `[batchSize, channels, depths, rows, cols]`\n *\n * Output shape\n * - If `dataFormat=channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, pooledDepths, pooledRows, pooledCols, channels]`\n * - If `dataFormat=channelsFirst`:\n * 5D tensor with shape:\n * `[batchSize, channels, pooledDepths, pooledRows, pooledCols]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function maxPooling3d(args: Pooling3DLayerArgs) {\n return new MaxPooling3D(args);\n}\n\n// Recurrent Layers.\n\n/**\n * Gated Recurrent Unit - Cho et al. 2014.\n *\n * This is an `RNN` layer consisting of one `GRUCell`. However, unlike\n * the underlying `GRUCell`, the `apply` method of `SimpleRNN` operates\n * on a sequence of inputs. The shape of the input (not including the first,\n * batch dimension) needs to be at least 2-D, with the first dimension being\n * time steps. For example:\n *\n * ```js\n * const rnn = tf.layers.gru({units: 8, returnSequences: true});\n *\n * // Create an input with 10 time steps.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the `GRUCell`'s number of units.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function gru(args: GRULayerArgs) {\n return new GRU(args);\n}\n\n/**\n * Cell class for `GRU`.\n *\n * `GRUCell` is distinct from the `RNN` subclass `GRU` in that its\n * `apply` method takes the input data of only a single time step and returns\n * the cell's output at the time step, while `GRU` takes the input data\n * over a number of time steps. For example:\n *\n * ```js\n * const cell = tf.layers.gruCell({units: 2});\n * const input = tf.input({shape: [10]});\n * const output = cell.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10]: This is the cell's output at a single time step. The 1st\n * // dimension is the unknown batch size.\n * ```\n *\n * Instance(s) of `GRUCell` can be used to construct `RNN` layers. The\n * most typical use of this workflow is to combine a number of cells into a\n * stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an\n * RNN. For example:\n *\n * ```js\n * const cells = [\n * tf.layers.gruCell({units: 4}),\n * tf.layers.gruCell({units: 8}),\n * ];\n * const rnn = tf.layers.rnn({cell: cells, returnSequences: true});\n *\n * // Create an input with 10 time steps and a length-20 vector at each step.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the last `gruCell`'s number of units.\n * ```\n *\n * To create an `RNN` consisting of only *one* `GRUCell`, use the\n * `tf.layers.gru`.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function gruCell(args: GRUCellLayerArgs) {\n return new GRUCell(args);\n}\n\n/**\n * Long-Short Term Memory layer - Hochreiter 1997.\n *\n * This is an `RNN` layer consisting of one `LSTMCell`. However, unlike\n * the underlying `LSTMCell`, the `apply` method of `LSTM` operates\n * on a sequence of inputs. The shape of the input (not including the first,\n * batch dimension) needs to be at least 2-D, with the first dimension being\n * time steps. For example:\n *\n * ```js\n * const lstm = tf.layers.lstm({units: 8, returnSequences: true});\n *\n * // Create an input with 10 time steps.\n * const input = tf.input({shape: [10, 20]});\n * const output = lstm.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the `LSTMCell`'s number of units.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function lstm(args: LSTMLayerArgs) {\n return new LSTM(args);\n}\n\n/**\n * Cell class for `LSTM`.\n *\n * `LSTMCell` is distinct from the `RNN` subclass `LSTM` in that its\n * `apply` method takes the input data of only a single time step and returns\n * the cell's output at the time step, while `LSTM` takes the input data\n * over a number of time steps. For example:\n *\n * ```js\n * const cell = tf.layers.lstmCell({units: 2});\n * const input = tf.input({shape: [10]});\n * const output = cell.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10]: This is the cell's output at a single time step. The 1st\n * // dimension is the unknown batch size.\n * ```\n *\n * Instance(s) of `LSTMCell` can be used to construct `RNN` layers. The\n * most typical use of this workflow is to combine a number of cells into a\n * stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an\n * RNN. For example:\n *\n * ```js\n * const cells = [\n * tf.layers.lstmCell({units: 4}),\n * tf.layers.lstmCell({units: 8}),\n * ];\n * const rnn = tf.layers.rnn({cell: cells, returnSequences: true});\n *\n * // Create an input with 10 time steps and a length-20 vector at each step.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the last `lstmCell`'s number of units.\n * ```\n *\n * To create an `RNN` consisting of only *one* `LSTMCell`, use the\n * `tf.layers.lstm`.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function lstmCell(args: LSTMCellLayerArgs) {\n return new LSTMCell(args);\n}\n\n/**\n * Fully-connected RNN where the output is to be fed back to input.\n *\n * This is an `RNN` layer consisting of one `SimpleRNNCell`. However, unlike\n * the underlying `SimpleRNNCell`, the `apply` method of `SimpleRNN` operates\n * on a sequence of inputs. The shape of the input (not including the first,\n * batch dimension) needs to be at least 2-D, with the first dimension being\n * time steps. For example:\n *\n * ```js\n * const rnn = tf.layers.simpleRNN({units: 8, returnSequences: true});\n *\n * // Create an input with 10 time steps.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the `SimpleRNNCell`'s number of units.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function simpleRNN(args: SimpleRNNLayerArgs) {\n return new SimpleRNN(args);\n}\n\n/**\n * Cell class for `SimpleRNN`.\n *\n * `SimpleRNNCell` is distinct from the `RNN` subclass `SimpleRNN` in that its\n * `apply` method takes the input data of only a single time step and returns\n * the cell's output at the time step, while `SimpleRNN` takes the input data\n * over a number of time steps. For example:\n *\n * ```js\n * const cell = tf.layers.simpleRNNCell({units: 2});\n * const input = tf.input({shape: [10]});\n * const output = cell.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10]: This is the cell's output at a single time step. The 1st\n * // dimension is the unknown batch size.\n * ```\n *\n * Instance(s) of `SimpleRNNCell` can be used to construct `RNN` layers. The\n * most typical use of this workflow is to combine a number of cells into a\n * stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an\n * RNN. For example:\n *\n * ```js\n * const cells = [\n * tf.layers.simpleRNNCell({units: 4}),\n * tf.layers.simpleRNNCell({units: 8}),\n * ];\n * const rnn = tf.layers.rnn({cell: cells, returnSequences: true});\n *\n * // Create an input with 10 time steps and a length-20 vector at each step.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the last `SimpleRNNCell`'s number of units.\n * ```\n *\n * To create an `RNN` consisting of only *one* `SimpleRNNCell`, use the\n * `tf.layers.simpleRNN`.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function simpleRNNCell(args: SimpleRNNCellLayerArgs) {\n return new SimpleRNNCell(args);\n}\n\n/**\n * Convolutional LSTM layer - Xingjian Shi 2015.\n *\n * This is a `ConvRNN2D` layer consisting of one `ConvLSTM2DCell`. However,\n * unlike the underlying `ConvLSTM2DCell`, the `apply` method of `ConvLSTM2D`\n * operates on a sequence of inputs. The shape of the input (not including the\n * first, batch dimension) needs to be 4-D, with the first dimension being time\n * steps. For example:\n *\n * ```js\n * const filters = 3;\n * const kernelSize = 3;\n *\n * const batchSize = 4;\n * const sequenceLength = 2;\n * const size = 5;\n * const channels = 3;\n *\n * const inputShape = [batchSize, sequenceLength, size, size, channels];\n * const input = tf.ones(inputShape);\n *\n * const layer = tf.layers.convLstm2d({filters, kernelSize});\n *\n * const output = layer.apply(input);\n * ```\n */\n/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */\nexport function convLstm2d(args: ConvLSTM2DArgs) {\n return new ConvLSTM2D(args);\n}\n\n/**\n * Cell class for `ConvLSTM2D`.\n *\n * `ConvLSTM2DCell` is distinct from the `ConvRNN2D` subclass `ConvLSTM2D` in\n * that its `call` method takes the input data of only a single time step and\n * returns the cell's output at the time step, while `ConvLSTM2D` takes the\n * input data over a number of time steps. For example:\n *\n * ```js\n * const filters = 3;\n * const kernelSize = 3;\n *\n * const sequenceLength = 1;\n * const size = 5;\n * const channels = 3;\n *\n * const inputShape = [sequenceLength, size, size, channels];\n * const input = tf.ones(inputShape);\n *\n * const cell = tf.layers.convLstm2dCell({filters, kernelSize});\n *\n * cell.build(input.shape);\n *\n * const outputSize = size - kernelSize + 1;\n * const outShape = [sequenceLength, outputSize, outputSize, filters];\n *\n * const initialH = tf.zeros(outShape);\n * const initialC = tf.zeros(outShape);\n *\n * const [o, h, c] = cell.call([input, initialH, initialC], {});\n * ```\n */\n/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */\nexport function convLstm2dCell(args: ConvLSTM2DCellArgs) {\n return new ConvLSTM2DCell(args);\n}\n\n/**\n * Base class for recurrent layers.\n *\n * Input shape:\n * 3D tensor with shape `[batchSize, timeSteps, inputDim]`.\n *\n * Output shape:\n * - if `returnState`, an Array of tensors (i.e., `tf.Tensor`s). The first\n * tensor is the output. The remaining tensors are the states at the\n * last time step, each with shape `[batchSize, units]`.\n * - if `returnSequences`, the output will have shape\n * `[batchSize, timeSteps, units]`.\n * - else, the output will have shape `[batchSize, units]`.\n *\n * Masking:\n * This layer supports masking for input data with a variable number\n * of timesteps. To introduce masks to your data,\n * use an embedding layer with the `mask_zero` parameter\n * set to `True`.\n *\n * Notes on using statefulness in RNNs:\n * You can set RNN layers to be 'stateful', which means that the states\n * computed for the samples in one batch will be reused as initial states\n * for the samples in the next batch. This assumes a one-to-one mapping\n * between samples in different successive batches.\n *\n * To enable statefulness:\n * - specify `stateful: true` in the layer constructor.\n * - specify a fixed batch size for your model, by passing\n * if sequential model:\n * `batchInputShape=[...]` to the first layer in your model.\n * else for functional model with 1 or more Input layers:\n * `batchShape=[...]` to all the first layers in your model.\n * This is the expected shape of your inputs *including the batch size*.\n * It should be a tuple of integers, e.g. `(32, 10, 100)`.\n * - specify `shuffle=False` when calling fit().\n *\n * To reset the states of your model, call `.resetStates()` on either\n * a specific layer, or on your entire model.\n *\n * Note on specifying the initial state of RNNs\n * You can specify the initial state of RNN layers symbolically by\n * calling them with the option `initialState`. The value of\n * `initialState` should be a tensor or list of tensors representing\n * the initial state of the RNN layer.\n *\n * You can specify the initial state of RNN layers numerically by\n * calling `resetStates` with the keyword argument `states`. The value of\n * `states` should be a numpy array or list of numpy arrays representing\n * the initial state of the RNN layer.\n *\n * Note on passing external constants to RNNs\n * You can pass \"external\" constants to the cell using the `constants`\n * keyword argument of `RNN.call` method. This requires that the `cell.call`\n * method accepts the same keyword argument `constants`. Such constants\n * can be used to condition the cell transformation on additional static\n * inputs (not changing over time), a.k.a. an attention mechanism.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function rnn(args: RNNLayerArgs) {\n return new RNN(args);\n}\n\n/**\n * Wrapper allowing a stack of RNN cells to behave as a single cell.\n *\n * Used to implement efficient stacked RNNs.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function stackedRNNCells(args: StackedRNNCellsArgs){\n return new StackedRNNCells(args);\n}\n\n// Wrapper Layers.\n\n/** @doc {heading: 'Layers', subheading: 'Wrapper', namespace: 'layers'} */\nexport function bidirectional(args: BidirectionalLayerArgs) {\n return new Bidirectional(args);\n}\n\n/**\n * This wrapper applies a layer to every temporal slice of an input.\n *\n * The input should be at least 3D, and the dimension of the index `1` will be\n * considered to be the temporal dimension.\n *\n * Consider a batch of 32 samples, where each sample is a sequence of 10 vectors\n * of 16 dimensions. The batch input shape of the layer is then `[32, 10,\n * 16]`, and the `inputShape`, not including the sample dimension, is\n * `[10, 16]`.\n *\n * You can then use `TimeDistributed` to apply a `Dense` layer to each of the 10\n * timesteps, independently:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.timeDistributed({\n * layer: tf.layers.dense({units: 8}),\n * inputShape: [10, 16],\n * }));\n *\n * // Now model.outputShape = [null, 10, 8].\n * // The output will then have shape `[32, 10, 8]`.\n *\n * // In subsequent layers, there is no need for `inputShape`:\n * model.add(tf.layers.timeDistributed({layer: tf.layers.dense({units: 32})}));\n * console.log(JSON.stringify(model.outputs[0].shape));\n * // Now model.outputShape = [null, 10, 32].\n * ```\n *\n * The output will then have shape `[32, 10, 32]`.\n *\n * `TimeDistributed` can be used with arbitrary layers, not just `Dense`, for\n * instance a `Conv2D` layer.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.timeDistributed({\n * layer: tf.layers.conv2d({filters: 64, kernelSize: [3, 3]}),\n * inputShape: [10, 299, 299, 3],\n * }));\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Wrapper', namespace: 'layers'}\n */\nexport function timeDistributed(args: WrapperLayerArgs) {\n return new TimeDistributed(args);\n}\n\n// Aliases for pooling.\nexport const globalMaxPool1d = globalMaxPooling1d;\nexport const globalMaxPool2d = globalMaxPooling2d;\nexport const maxPool1d = maxPooling1d;\nexport const maxPool2d = maxPooling2d;\n\nexport {Layer, RNN, RNNCell, input /* alias for tf.input */};\n\n/**\n * Apply additive zero-centered Gaussian noise.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * This is useful to mitigate overfitting\n * (you could see it as a form of random data augmentation).\n * Gaussian Noise (GS) is a natural choice as corruption process\n * for real valued inputs.\n *\n * # Arguments\n * stddev: float, standard deviation of the noise distribution.\n *\n * # Input shape\n * Arbitrary. Use the keyword argument `input_shape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * # Output shape\n * Same shape as input.\n *\n * @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'}\n */\nexport function gaussianNoise(args: GaussianNoiseArgs) {\n return new GaussianNoise(args);\n}\n\n/**\n * Apply multiplicative 1-centered Gaussian noise.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * Arguments:\n * - `rate`: float, drop probability (as with `Dropout`).\n * The multiplicative noise will have\n * standard deviation `sqrt(rate / (1 - rate))`.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](\n * http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)\n *\n * @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'}\n */\nexport function gaussianDropout(args: GaussianDropoutArgs) {\n return new GaussianDropout(args);\n}\n\n/**\n * Applies Alpha Dropout to the input.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * Alpha Dropout is a `Dropout` that keeps mean and variance of inputs\n * to their original values, in order to ensure the self-normalizing property\n * even after this dropout.\n * Alpha Dropout fits well to Scaled Exponential Linear Units\n * by randomly setting activations to the negative saturation value.\n *\n * Arguments:\n * - `rate`: float, drop probability (as with `Dropout`).\n * The multiplicative noise will have\n * standard deviation `sqrt(rate / (1 - rate))`.\n * - `noise_shape`: A 1-D `Tensor` of type `int32`, representing the\n * shape for randomly generated keep/drop flags.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\n *\n * @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'}\n */\nexport function alphaDropout(args: AlphaDropoutArgs) {\n return new AlphaDropout(args);\n}\n\n/**\n * Masks a sequence by using a mask value to skip timesteps.\n *\n * If all features for a given sample timestep are equal to `mask_value`,\n * then the sample timestep will be masked (skipped) in all downstream layers\n * (as long as they support masking).\n *\n * If any downstream layer does not support masking yet receives such\n * an input mask, an exception will be raised.\n *\n * Arguments:\n * - `maskValue`: Either None or mask value to skip.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * @doc {heading: 'Layers', subheading: 'Mask', namespace: 'layers'}\n */\nexport function masking(args?: MaskingArgs) {\n return new Masking(args);\n}\n\n/**\n * A preprocessing layer which rescales input values to a new range.\n *\n * This layer rescales every value of an input (often an image) by multiplying\n * by `scale` and adding `offset`.\n *\n * For instance:\n * 1. To rescale an input in the ``[0, 255]`` range\n * to be in the `[0, 1]` range, you would pass `scale=1/255`.\n * 2. To rescale an input in the ``[0, 255]`` range to be in the `[-1, 1]`\n * range, you would pass `scale=1./127.5, offset=-1`.\n * The rescaling is applied both during training and inference. Inputs can be\n * of integer or floating point dtype, and by default the layer will output\n * floats.\n *\n * Arguments:\n * - `scale`: Float, the scale to apply to the inputs.\n * - `offset`: Float, the offset to apply to the inputs.\n *\n * Input shape:\n * Arbitrary.\n *\n * Output shape:\n * Same as input.\n *\n * @doc {heading: 'Layers', subheading: 'Rescaling', namespace: 'layers'}\n */\nexport function rescaling(args?: RescalingArgs) {\n return new Rescaling(args);\n}\n\n/**\n * A preprocessing layer which center crops images.\n *\n * This layers crops the central portion of the images to a target size. If an\n * image is smaller than the target size, it will be resized and cropped so as\n * to return the largest possible window in the image that matches the target\n * aspect ratio.\n *\n * Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and\n * of integer or floating point dtype.\n *\n * If the input height/width is even and the target height/width is odd (or\n * inversely), the input image is left-padded by 1 pixel.\n *\n * Arguments:\n * `height`: Integer, the height of the output shape.\n * `width`: Integer, the width of the output shape.\n *\n * Input shape:\n * 3D (unbatched) or 4D (batched) tensor with shape:\n * `(..., height, width, channels)`, in `channelsLast` format.\n *\n * Output shape:\n * 3D (unbatched) or 4D (batched) tensor with shape:\n * `(..., targetHeight, targetWidth, channels)`.\n *\n *\n * @doc {heading: 'Layers', subheading: 'CenterCrop', namespace: 'layers'}\n */\nexport function centerCrop(args?: CenterCropArgs) {\n return new CenterCrop(args);\n }\n\n/**\n * A preprocessing layer which resizes images.\n * This layer resizes an image input to a target height and width. The input\n * should be a 4D (batched) or 3D (unbatched) tensor in `\"channels_last\"`\n * format. Input pixel values can be of any range (e.g. `[0., 1.)` or `[0,\n * 255]`) and of interger or floating point dtype. By default, the layer will\n * output floats.\n *\n * Arguments:\n * - `height`: number, the height for the output tensor.\n * - `width`: number, the width for the output tensor.\n * - `interpolation`: string, the method for image resizing interpolation.\n * - `cropToAspectRatio`: boolean, whether to keep image aspect ratio.\n *\n * Input shape:\n * Arbitrary.\n *\n * Output shape:\n * height, width, num channels.\n *\n * @doc {heading: 'Layers', subheading: 'Resizing', namespace: 'layers'}\n */\nexport function resizing(args?: ResizingArgs) {\n return new Resizing(args);\n}\n\n/**\n * A preprocessing layer which encodes integer features.\n *\n * This layer provides options for condensing data into a categorical encoding\n * when the total number of tokens are known in advance. It accepts integer\n * values as inputs, and it outputs a dense representation of those\n * inputs.\n *\n * Arguments:\n *\n * numTokens: The total number of tokens the layer should support. All\n * inputs to the layer must integers in the range `0 <= value <\n * numTokens`, or an error will be thrown.\n *\n * outputMode: Specification for the output of the layer.\n * Defaults to `multiHot`. Values can be `oneHot`, `multiHot` or\n * `count`, configuring the layer as follows:\n *\n * oneHot: Encodes each individual element in the input into an\n * array of `numTokens` size, containing a 1 at the element index. If\n * the last dimension is size 1, will encode on that dimension. If the\n * last dimension is not size 1, will append a new dimension for the\n * encoded output.\n *\n * multiHot: Encodes each sample in the input into a single array\n * of `numTokens` size, containing a 1 for each vocabulary term\n * present in the sample. Treats the last dimension as the sample\n * dimension, if input shape is `(..., sampleLength)`, output shape\n * will be `(..., numTokens)`.\n *\n * count: Like `multiHot`, but the int array contains a count of\n * the number of times the token at that index appeared in the sample.\n *\n * For all output modes, currently only output up to rank 2 is supported.\n * Call arguments:\n * inputs: A 1D or 2D tensor of integer inputs.\n * countWeights: A tensor in the same shape as `inputs` indicating the\n * weight for each sample value when summing up in `count` mode. Not used\n * in `multiHot` or `oneHot` modes.\n *\n *\n * @doc {heading: 'Layers', subheading: 'CategoryEncoding', namespace: 'layers'}\n */\nexport function categoryEncoding(args: CategoryEncodingArgs) {\n return new CategoryEncoding(args);\n}\n\n /**\n * A preprocessing layer which randomly varies image width during training.\n *\n * This layer will randomly adjusts the width of a batch of images of a batch\n * of images by a random factor.\n *\n * The input should be a 3D (unbatched) or 4D (batched) tensor in\n * the `\"channels_last\"` image data format. Input pixel values can be of any\n * range (e.g. `[0., 1.)` or `[0, 255]`) and of integer or floating point\n * dtype. By default, the layer will output floats. By default, this layer is\n * inactive during inference. For an overview and full list of preprocessing\n * layers, see the preprocessing [guide]\n * (https://www.tensorflow.org/guide/keras/preprocessing_layers).\n *\n * Arguments:\n *\n * factor:\n * A positive float (fraction of original width), or a tuple of size 2\n * representing lower and upper bound for resizing vertically.\n * When represented as a single float, this value is used for both the upper\n * and lower bound. For instance, `factor=(0.2, 0.3)` results in an output\n * with width changed by a random amount in the range `[20%, 30%]`.\n * `factor=(-0.2, 0.3)` results in an output with width changed by a random\n * amount in the range `[-20%, +30%]`. `factor=0.2` results in an output\n * with width changed by a random amount in the range `[-20%, +20%]`.\n * interpolation:\n * String, the interpolation method.\n * Defaults to `bilinear`.\n * Supports `\"bilinear\"`, `\"nearest\"`.\n * The tf methods `\"bicubic\"`, `\"area\"`, `\"lanczos3\"`, `\"lanczos5\"`,\n * `\"gaussian\"`, `\"mitchellcubic\"` are unimplemented in tfjs.\n * seed:\n * Integer. Used to create a random seed.\n *\n * Input shape:\n * 3D (unbatched) or 4D (batched) tensor with shape:\n * `(..., height, width, channels)`, in `\"channels_last\"` format.\n * Output shape:\n * 3D (unbatched) or 4D (batched) tensor with shape:\n * `(..., height, random_width, channels)`.\n *\n *\n * @doc {heading: 'Layers', subheading: 'RandomWidth', namespace: 'layers'}\n */\n export function randomWidth(args: RandomWidthArgs) {\n return new RandomWidth(args);\n }\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\nimport {Tensor} from '@tensorflow/tfjs-core';\n\nimport * as losses from './losses';\nimport * as metrics from './metrics';\n\n/**\n * Binary accuracy metric function.\n *\n * `yTrue` and `yPred` can have 0-1 values. Example:\n * ```js\n * const x = tf.tensor2d([[1, 1, 1, 1], [0, 0, 0, 0]], [2, 4]);\n * const y = tf.tensor2d([[1, 0, 1, 0], [0, 0, 0, 1]], [2, 4]);\n * const accuracy = tf.metrics.binaryAccuracy(x, y);\n * accuracy.print();\n * ```\n *\n * `yTrue` and `yPred` can also have floating-number values between 0 and 1, in\n * which case the values will be thresholded at 0.5 to yield 0-1 values (i.e.,\n * a value >= 0.5 and <= 1.0 is interpreted as 1).\n *\n * Example:\n * ```js\n * const x = tf.tensor1d([1, 1, 1, 1, 0, 0, 0, 0]);\n * const y = tf.tensor1d([0.2, 0.4, 0.6, 0.8, 0.2, 0.3, 0.4, 0.7]);\n * const accuracy = tf.metrics.binaryAccuracy(x, y);\n * accuracy.print();\n * ```\n *\n * @param yTrue Binary Tensor of truth.\n * @param yPred Binary Tensor of prediction.\n * @return Accuracy Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function binaryAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.binaryAccuracy(yTrue, yPred);\n}\n\n/**\n * Binary crossentropy metric function.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d([[0], [1], [1], [1]]);\n * const y = tf.tensor2d([[0], [0], [0.5], [1]]);\n * const crossentropy = tf.metrics.binaryCrossentropy(x, y);\n * crossentropy.print();\n * ```\n *\n * @param yTrue Binary Tensor of truth.\n * @param yPred Binary Tensor of prediction, probabilities for the `1` case.\n * @return Accuracy Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function binaryCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.binaryCrossentropy(yTrue, yPred);\n}\n\n/**\n * Sparse categorical accuracy metric function.\n *\n * Example:\n * ```js\n *\n * const yTrue = tf.tensor1d([1, 1, 2, 2, 0]);\n * const yPred = tf.tensor2d(\n * [[0, 1, 0], [1, 0, 0], [0, 0.4, 0.6], [0, 0.6, 0.4], [0.7, 0.3, 0]]);\n * const crossentropy = tf.metrics.sparseCategoricalAccuracy(yTrue, yPred);\n * crossentropy.print();\n * ```\n *\n * @param yTrue True labels: indices.\n * @param yPred Predicted probabilities or logits.\n * @returns Accuracy tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function sparseCategoricalAccuracy(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.sparseCategoricalAccuracy(yTrue, yPred);\n}\n\n/**\n * Categorical accuracy metric function.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d([[0, 0, 0, 1], [0, 0, 0, 1]]);\n * const y = tf.tensor2d([[0.1, 0.8, 0.05, 0.05], [0.1, 0.05, 0.05, 0.8]]);\n * const accuracy = tf.metrics.categoricalAccuracy(x, y);\n * accuracy.print();\n * ```\n *\n * @param yTrue Binary Tensor of truth: one-hot encoding of categories.\n * @param yPred Binary Tensor of prediction: probabilities or logits for the\n * same categories as in `yTrue`.\n * @return Accuracy Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function categoricalAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.categoricalAccuracy(yTrue, yPred);\n}\n\n/**\n * Categorical crossentropy between an output tensor and a target tensor.\n *\n * @param target A tensor of the same shape as `output`.\n * @param output A tensor resulting from a softmax (unless `fromLogits` is\n * `true`, in which case `output` is expected to be the logits).\n * @param fromLogits Boolean, whether `output` is the result of a softmax, or is\n * a tensor of logits.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function categoricalCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.categoricalCrossentropy(yTrue, yPred);\n}\n\n/**\n * Computes the precision of the predictions with respect to the labels.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d(\n * [\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [1, 0, 0, 0],\n * [0, 0, 1, 0]\n * ]\n * );\n *\n * const y = tf.tensor2d(\n * [\n * [0, 0, 1, 0],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 1, 0, 0]\n * ]\n * );\n *\n * const precision = tf.metrics.precision(x, y);\n * precision.print();\n * ```\n *\n * @param yTrue The ground truth values. Expected to contain only 0-1 values.\n * @param yPred The predicted values. Expected to contain only 0-1 values.\n * @return Precision Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function precision(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.precision(yTrue, yPred);\n}\n\n/**\n * Computes the recall of the predictions with respect to the labels.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d(\n * [\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [1, 0, 0, 0],\n * [0, 0, 1, 0]\n * ]\n * );\n *\n * const y = tf.tensor2d(\n * [\n * [0, 0, 1, 0],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 1, 0, 0]\n * ]\n * );\n *\n * const recall = tf.metrics.recall(x, y);\n * recall.print();\n * ```\n *\n * @param yTrue The ground truth values. Expected to contain only 0-1 values.\n * @param yPred The predicted values. Expected to contain only 0-1 values.\n * @return Recall Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function recall(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.recall(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Cosine proximity.\n *\n * Mathematically, cosine proximity is defined as:\n * `-sum(l2Normalize(yTrue) * l2Normalize(yPred))`,\n * wherein `l2Normalize()` normalizes the L2 norm of the input to 1 and `*`\n * represents element-wise multiplication.\n *\n * ```js\n * const yTrue = tf.tensor2d([[1, 0], [1, 0]]);\n * const yPred = tf.tensor2d([[1 / Math.sqrt(2), 1 / Math.sqrt(2)], [0, 1]]);\n * const proximity = tf.metrics.cosineProximity(yTrue, yPred);\n * proximity.print();\n * ```\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Cosine proximity Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function cosineProximity(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.cosineProximity(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Mean absolute error.\n *\n * Mathematically, mean absolute error is defined as:\n * `mean(abs(yPred - yTrue))`,\n * wherein the `mean` is applied over feature dimensions.\n *\n * ```js\n * const yTrue = tf.tensor2d([[0, 1], [0, 0], [2, 3]]);\n * const yPred = tf.tensor2d([[0, 1], [0, 1], [-2, -3]]);\n * const mse = tf.metrics.meanAbsoluteError(yTrue, yPred);\n * mse.print();\n * ```\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Mean absolute error Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function meanAbsoluteError(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsoluteError(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Mean absolute percentage error.\n *\n * ```js\n * const yTrue = tf.tensor2d([[0, 1], [10, 20]]);\n * const yPred = tf.tensor2d([[0, 1], [11, 24]]);\n * const mse = tf.metrics.meanAbsolutePercentageError(yTrue, yPred);\n * mse.print();\n * ```\n *\n * Aliases: `tf.metrics.MAPE`, `tf.metrics.mape`.\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Mean absolute percentage error Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function meanAbsolutePercentageError(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsolutePercentageError(yTrue, yPred);\n}\n\nexport function MAPE(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsolutePercentageError(yTrue, yPred);\n}\n\nexport function mape(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsolutePercentageError(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Mean squared error.\n *\n * ```js\n * const yTrue = tf.tensor2d([[0, 1], [3, 4]]);\n * const yPred = tf.tensor2d([[0, 1], [-3, -4]]);\n * const mse = tf.metrics.meanSquaredError(yTrue, yPred);\n * mse.print();\n * ```\n *\n * Aliases: `tf.metrics.MSE`, `tf.metrics.mse`.\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Mean squared error Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function meanSquaredError(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanSquaredError(yTrue, yPred);\n}\n\nexport function MSE(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanSquaredError(yTrue, yPred);\n}\n\nexport function mse(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanSquaredError(yTrue, yPred);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\nimport * as regularizers from './regularizers';\n// tslint:disable-next-line:max-line-length\nimport {L1Args, L1L2, L1L2Args, L2Args, Regularizer} from './regularizers';\n\n/**\n * Regularizer for L1 and L2 regularization.\n *\n * Adds a term to the loss to penalize large weights:\n * loss += sum(l1 * abs(x)) + sum(l2 * x^2)\n *\n * @doc {heading: 'Regularizers', namespace: 'regularizers'}\n */\nexport function l1l2(config?: L1L2Args): Regularizer {\n return new L1L2(config);\n}\n\n/**\n * Regularizer for L1 regularization.\n *\n * Adds a term to the loss to penalize large weights:\n * loss += sum(l1 * abs(x))\n * @param args l1 config.\n *\n * @doc {heading: 'Regularizers', namespace: 'regularizers'}\n */\nexport function l1(config?: L1Args): Regularizer {\n return regularizers.l1(config);\n}\n\n/**\n * Regularizer for L2 regularization.\n *\n * Adds a term to the loss to penalize large weights:\n * loss += sum(l2 * x^2)\n * @param args l2 config.\n *\n * @doc {heading: 'Regularizers', namespace: 'regularizers'}\n */\nexport function l2(config?: L2Args): Regularizer {\n return regularizers.l2(config);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/callbacks.py */\n\nimport {BaseCallback} from './base_callbacks';\nimport {Container} from './engine/container';\nimport {LayersModel} from './engine/training';\nimport {NotImplementedError} from './errors';\nimport {Logs, resolveScalarsInLogs} from './logs';\n\nexport abstract class Callback extends BaseCallback {\n /** Instance of `keras.models.Model`. Reference of the model being trained. */\n model: LayersModel = null;\n\n override 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 * 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 override 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 override 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 override 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 */\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 // Not a legal value for DataType. Used to indicate a DataType field\n // has not been set.\n DT_INVALID = 0,\n\n // Data types that all computation devices are expected to be\n // capable to support.\n DT_FLOAT = 1,\n DT_DOUBLE = 2,\n DT_INT32 = 3,\n DT_UINT8 = 4,\n DT_INT16 = 5,\n DT_INT8 = 6,\n DT_STRING = 7,\n DT_COMPLEX64 = 8, // Single-precision complex\n DT_INT64 = 9,\n DT_BOOL = 10,\n DT_QINT8 = 11, // Quantized int8\n DT_QUINT8 = 12, // Quantized uint8\n DT_QINT32 = 13, // Quantized int32\n DT_BFLOAT16 = 14, // Float32 truncated to 16 bits. Only for cast ops.\n DT_QINT16 = 15, // Quantized int16\n DT_QUINT16 = 16, // Quantized uint16\n DT_UINT16 = 17,\n DT_COMPLEX128 = 18, // Double-precision complex\n DT_HALF = 19,\n DT_RESOURCE = 20,\n DT_VARIANT = 21, // Arbitrary C++ data types\n DT_UINT32 = 22,\n DT_UINT64 = 23,\n\n // Do not use! These are only for parameters. Every enum above\n // should have a corresponding value below (verified by types_test).\n DT_FLOAT_REF = 101,\n DT_DOUBLE_REF = 102,\n DT_INT32_REF = 103,\n DT_UINT8_REF = 104,\n DT_INT16_REF = 105,\n DT_INT8_REF = 106,\n DT_STRING_REF = 107,\n DT_COMPLEX64_REF = 108,\n DT_INT64_REF = 109,\n DT_BOOL_REF = 110,\n DT_QINT8_REF = 111,\n DT_QUINT8_REF = 112,\n DT_QINT32_REF = 113,\n DT_BFLOAT16_REF = 114,\n DT_QINT16_REF = 115,\n DT_QUINT16_REF = 116,\n DT_UINT16_REF = 117,\n DT_COMPLEX128_REF = 118,\n DT_HALF_REF = 119,\n DT_RESOURCE_REF = 120,\n DT_VARIANT_REF = 121,\n DT_UINT32_REF = 122,\n DT_UINT64_REF = 123,\n}\n\n/** Properties of a TensorShape. */\nexport declare interface ITensorShape {\n /** TensorShape dim */\n dim?: (TensorShape.IDim[]|null);\n\n /** TensorShape unknownRank */\n unknownRank?: (boolean|null);\n}\n\nexport namespace TensorShape {\n /** Properties of a Dim. */\n export declare interface IDim {\n /** Dim size */\n size?: (number|string|null);\n\n /** Dim name */\n name?: (string|null);\n }\n}\n\n/** Properties of a Tensor. */\nexport declare interface ITensor {\n /** Tensor dtype */\n dtype?: (DataType|null);\n\n /** Tensor tensorShape */\n tensorShape?: (ITensorShape|null);\n\n /** Tensor versionNumber */\n versionNumber?: (number|null);\n\n /** Tensor tensorContent */\n tensorContent?: (Uint8Array|null);\n\n /** Tensor floatVal */\n floatVal?: (number[]|null);\n\n /** Tensor doubleVal */\n doubleVal?: (number[]|null);\n\n /** Tensor intVal */\n intVal?: (number[]|null);\n\n /** Tensor stringVal */\n stringVal?: (Uint8Array[]|null);\n\n /** Tensor scomplexVal */\n scomplexVal?: (number[]|null);\n\n /** Tensor int64Val */\n int64Val?: ((number | string)[]|null);\n\n /** Tensor boolVal */\n boolVal?: (boolean[]|null);\n\n /** Tensor uint32Val */\n uint32Val?: (number[]|null);\n\n /** Tensor uint64Val */\n uint64Val?: ((number | string)[]|null);\n}\n\n/** Properties of an AttrValue. */\nexport declare interface IAttrValue {\n /** AttrValue list */\n list?: (AttrValue.IListValue|null);\n\n /** AttrValue s */\n s?: (string|null);\n\n /** AttrValue i */\n i?: (number|string|null);\n\n /** AttrValue f */\n f?: (number|null);\n\n /** AttrValue b */\n b?: (boolean|null);\n\n /** AttrValue type */\n type?: (DataType|null);\n\n /** AttrValue shape */\n shape?: (ITensorShape|null);\n\n /** AttrValue tensor */\n tensor?: (ITensor|null);\n\n /** AttrValue placeholder */\n placeholder?: (string|null);\n\n /** AttrValue func */\n func?: (INameAttrList|null);\n}\n\nexport namespace AttrValue {\n /** Properties of a ListValue. */\n export declare interface IListValue {\n /** ListValue s */\n s?: (string[]|null);\n\n /** ListValue i */\n i?: ((number | string)[]|null);\n\n /** ListValue f */\n f?: (number[]|null);\n\n /** ListValue b */\n b?: (boolean[]|null);\n\n /** ListValue type */\n type?: (DataType[]|null);\n\n /** ListValue shape */\n shape?: (ITensorShape[]|null);\n\n /** ListValue tensor */\n tensor?: (ITensor[]|null);\n\n /** ListValue func */\n func?: (INameAttrList[]|null);\n }\n}\n\n/** Properties of a NameAttrList. */\nexport declare interface INameAttrList {\n /** NameAttrList name */\n name?: (string|null);\n\n /** NameAttrList attr */\n attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a NodeDef. */\nexport declare interface INodeDef {\n /** NodeDef name */\n name?: (string|null);\n\n /** NodeDef op */\n op?: (string|null);\n\n /** NodeDef input */\n input?: (string[]|null);\n\n /** NodeDef device */\n device?: (string|null);\n\n /** NodeDef attr */\n attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a VersionDef. */\nexport declare interface IVersionDef {\n /** VersionDef producer */\n producer?: (number|null);\n\n /** VersionDef minConsumer */\n minConsumer?: (number|null);\n\n /** VersionDef badConsumers */\n badConsumers?: (number[]|null);\n}\n\n/** Properties of a GraphDef. */\nexport declare interface IGraphDef {\n /** GraphDef node */\n node?: (INodeDef[]|null);\n\n /** GraphDef versions */\n versions?: (IVersionDef|null);\n\n /** GraphDef library */\n library?: (IFunctionDefLibrary|null);\n}\n\n/** Properties of a CollectionDef. */\nexport declare interface ICollectionDef {\n /** CollectionDef nodeList */\n nodeList?: (CollectionDef.INodeList|null);\n\n /** CollectionDef bytesList */\n bytesList?: (CollectionDef.IBytesList|null);\n\n /** CollectionDef int64List */\n int64List?: (CollectionDef.IInt64List|null);\n\n /** CollectionDef floatList */\n floatList?: (CollectionDef.IFloatList|null);\n\n /** CollectionDef anyList */\n anyList?: (CollectionDef.IAnyList|null);\n}\n\nexport namespace CollectionDef {\n /** Properties of a NodeList. */\n export declare interface INodeList {\n /** NodeList value */\n value?: (string[]|null);\n }\n\n /** Properties of a BytesList. */\n export declare interface IBytesList {\n /** BytesList value */\n value?: (Uint8Array[]|null);\n }\n\n /** Properties of an Int64List. */\n export declare interface IInt64List {\n /** Int64List value */\n value?: ((number | string)[]|null);\n }\n\n /** Properties of a FloatList. */\n export declare interface IFloatList {\n /** FloatList value */\n value?: (number[]|null);\n }\n\n /** Properties of an AnyList. */\n export declare interface IAnyList {\n /** AnyList value */\n value?: (IAny[]|null);\n }\n}\n\n/** Properties of a SaverDef. */\nexport declare interface ISaverDef {\n /** SaverDef filenameTensorName */\n filenameTensorName?: (string|null);\n\n /** SaverDef saveTensorName */\n saveTensorName?: (string|null);\n\n /** SaverDef restoreOpName */\n restoreOpName?: (string|null);\n\n /** SaverDef maxToKeep */\n maxToKeep?: (number|null);\n\n /** SaverDef sharded */\n sharded?: (boolean|null);\n\n /** SaverDef keepCheckpointEveryNHours */\n keepCheckpointEveryNHours?: (number|null);\n\n /** SaverDef version */\n version?: (SaverDef.CheckpointFormatVersion|null);\n}\n\nexport namespace SaverDef {\n /** CheckpointFormatVersion enum. */\n export enum CheckpointFormatVersion {'LEGACY' = 0, 'V1' = 1, 'V2' = 2}\n}\n\n/** Properties of a TensorInfo. */\nexport declare interface ITensorInfo {\n /** TensorInfo name */\n name?: (string|null);\n\n /** TensorInfo cooSparse */\n cooSparse?: (TensorInfo.ICooSparse|null);\n\n /** TensorInfo dtype */\n dtype?: (DataType|string|null);\n\n /** TensorInfo tensorShape */\n tensorShape?: (ITensorShape|null);\n\n /** Resource id tensor was originally assigned to. */\n resourceId?: (number|null);\n}\n\nexport namespace TensorInfo {\n /** Properties of a CooSparse. */\n export declare interface ICooSparse {\n /** CooSparse valuesTensorName */\n valuesTensorName?: (string|null);\n\n /** CooSparse indicesTensorName */\n indicesTensorName?: (string|null);\n\n /** CooSparse denseShapeTensorName */\n denseShapeTensorName?: (string|null);\n }\n}\n\n/** Properties of a SignatureDef. */\nexport declare interface ISignatureDef {\n /** SignatureDef inputs */\n inputs?: ({[k: string]: ITensorInfo}|null);\n\n /** SignatureDef outputs */\n outputs?: ({[k: string]: ITensorInfo}|null);\n\n /** SignatureDef methodName */\n methodName?: (string|null);\n}\n\n/** Properties of an AssetFileDef. */\nexport declare interface IAssetFileDef {\n /** AssetFileDef tensorInfo */\n tensorInfo?: (ITensorInfo|null);\n\n /** AssetFileDef filename */\n filename?: (string|null);\n}\n\n/** Properties of an OpDef. */\nexport declare interface IOpDef {\n /** OpDef name */\n name?: (string|null);\n\n /** OpDef inputArg */\n inputArg?: (OpDef.IArgDef[]|null);\n\n /** OpDef outputArg */\n outputArg?: (OpDef.IArgDef[]|null);\n\n /** OpDef attr */\n attr?: (OpDef.IAttrDef[]|null);\n\n /** OpDef deprecation */\n deprecation?: (OpDef.IOpDeprecation|null);\n\n /** OpDef summary */\n summary?: (string|null);\n\n /** OpDef description */\n description?: (string|null);\n\n /** OpDef isCommutative */\n isCommutative?: (boolean|null);\n\n /** OpDef isAggregate */\n isAggregate?: (boolean|null);\n\n /** OpDef isStateful */\n isStateful?: (boolean|null);\n\n /** OpDef allowsUninitializedInput */\n allowsUninitializedInput?: (boolean|null);\n}\n\nexport namespace OpDef {\n /** Properties of an ArgDef. */\n export declare interface IArgDef {\n /** ArgDef name */\n name?: (string|null);\n\n /** ArgDef description */\n description?: (string|null);\n\n /** ArgDef type */\n type?: (DataType|null);\n\n /** ArgDef typeAttr */\n typeAttr?: (string|null);\n\n /** ArgDef numberAttr */\n numberAttr?: (string|null);\n\n /** ArgDef typeListAttr */\n typeListAttr?: (string|null);\n\n /** ArgDef isRef */\n isRef?: (boolean|null);\n }\n\n /** Properties of an AttrDef. */\n export declare interface IAttrDef {\n /** AttrDef name */\n name?: (string|null);\n\n /** AttrDef type */\n type?: (string|null);\n\n /** AttrDef defaultValue */\n defaultValue?: (IAttrValue|null);\n\n /** AttrDef description */\n description?: (string|null);\n\n /** AttrDef hasMinimum */\n hasMinimum?: (boolean|null);\n\n /** AttrDef minimum */\n minimum?: (number|string|null);\n\n /** AttrDef allowedValues */\n allowedValues?: (IAttrValue|null);\n }\n\n /** Properties of an OpDeprecation. */\n export declare interface IOpDeprecation {\n /** OpDeprecation version */\n version?: (number|null);\n\n /** OpDeprecation explanation */\n explanation?: (string|null);\n }\n}\n\n/** Properties of an OpList. */\nexport declare interface IOpList {\n /** OpList op */\n op?: (IOpDef[]|null);\n}\n\n/** Properties of a MetaGraphDef. */\nexport declare interface IMetaGraphDef {\n /** MetaGraphDef metaInfoDef */\n metaInfoDef?: (MetaGraphDef.IMetaInfoDef|null);\n\n /** MetaGraphDef graphDef */\n graphDef?: (IGraphDef|null);\n\n /** MetaGraphDef saverDef */\n saverDef?: (ISaverDef|null);\n\n /** MetaGraphDef collectionDef */\n collectionDef?: ({[k: string]: ICollectionDef}|null);\n\n /** MetaGraphDef signatureDef */\n signatureDef?: ({[k: string]: ISignatureDef}|null);\n\n /** MetaGraphDef assetFileDef */\n assetFileDef?: (IAssetFileDef[]|null);\n}\n\nexport namespace MetaGraphDef {\n /** Properties of a MetaInfoDef. */\n export declare interface IMetaInfoDef {\n /** MetaInfoDef metaGraphVersion */\n metaGraphVersion?: (string|null);\n\n /** MetaInfoDef strippedOpList */\n strippedOpList?: (IOpList|null);\n\n /** MetaInfoDef anyInfo */\n anyInfo?: (IAny|null);\n\n /** MetaInfoDef tags */\n tags?: (string[]|null);\n\n /** MetaInfoDef tensorflowVersion */\n tensorflowVersion?: (string|null);\n\n /** MetaInfoDef tensorflowGitVersion */\n tensorflowGitVersion?: (string|null);\n }\n}\n\n/** Properties of a SavedModel. */\nexport declare interface ISavedModel {\n /** SavedModel savedModelSchemaVersion */\n savedModelSchemaVersion?: (number|string|null);\n\n /** SavedModel metaGraphs */\n metaGraphs?: (IMetaGraphDef[]|null);\n}\n\n/** Properties of a FunctionDefLibrary. */\nexport declare interface IFunctionDefLibrary {\n /** FunctionDefLibrary function */\n 'function'?: (IFunctionDef[]|null);\n\n /** FunctionDefLibrary gradient */\n gradient?: (IGradientDef[]|null);\n}\n\n/** Properties of a FunctionDef. */\nexport declare interface IFunctionDef {\n /** FunctionDef signature */\n signature?: (IOpDef|null);\n\n /** FunctionDef attr */\n attr?: ({[k: string]: IAttrValue}|null);\n\n /** FunctionDef nodeDef */\n nodeDef?: (INodeDef[]|null);\n\n /** FunctionDef ret */\n ret?: ({[k: string]: string}|null);\n}\n\n/** Properties of a GradientDef. */\nexport declare interface IGradientDef {\n /** GradientDef functionName */\n functionName?: (string|null);\n\n /** GradientDef gradientFunc */\n gradientFunc?: (string|null);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nconst ENV = env();\n\n/** Whether to keep intermediate tensors. */\nENV.registerFlag('KEEP_INTERMEDIATE_TENSORS', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Keep intermediate tensors is ON. This will print the values of all ' +\n 'intermediate tensors during model inference. Not all models ' +\n 'support this mode. For details, check e2e/benchmarks/ ' +\n 'model_config.js. This significantly impacts performance.');\n }\n});\n","\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpExecutor, OpMapper} from '../types';\n\nconst CUSTOM_OPS: {[key: string]: OpMapper} = {};\n\n/**\n * Register an Op for graph model executor. This allows you to register\n * TensorFlow custom op or override existing op.\n *\n * Here is an example of registering a new MatMul Op.\n * ```js\n * const customMatmul = (node) =>\n * tf.matMul(\n * node.inputs[0], node.inputs[1],\n * node.attrs['transpose_a'], node.attrs['transpose_b']);\n *\n * tf.registerOp('MatMul', customMatmul);\n * ```\n * The inputs and attrs of the node object are based on the TensorFlow op\n * registry.\n *\n * @param name The Tensorflow Op name.\n * @param opFunc An op function which is called with the current graph node\n * during execution and needs to return a tensor or a list of tensors. The node\n * has the following attributes:\n * - attr: A map from attribute name to its value\n * - inputs: A list of input tensors\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function registerOp(name: string, opFunc: OpExecutor) {\n const opMapper: OpMapper = {\n tfOpName: name,\n category: 'custom',\n inputs: [],\n attrs: [],\n customExecutor: opFunc\n };\n\n CUSTOM_OPS[name] = opMapper;\n}\n\n/**\n * Retrieve the OpMapper object for the registered op.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function getRegisteredOp(name: string): OpMapper {\n return CUSTOM_OPS[name];\n}\n\n/**\n * Deregister the Op for graph model executor.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function deregisterOp(name: string) {\n delete CUSTOM_OPS[name];\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {clone, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {ResourceManager} from '../../executor/resource_manager';\nimport {Node, ValueType} from '../types';\n\nexport function getParamValue(\n paramName: string, node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, resourceManager?: ResourceManager): ValueType {\n const inputParam = node.inputParams[paramName];\n if (inputParam && inputParam.inputIndexStart !== undefined) {\n const start = inputParam.inputIndexStart;\n const end = inputParam.inputIndexEnd === 0 ?\n undefined :\n (inputParam.inputIndexEnd === undefined ? start + 1 :\n inputParam.inputIndexEnd);\n const shiftedStart = start < 0 ? node.inputNames.length + start : start;\n if (inputParam.type === 'tensor') {\n return getTensor(\n node.inputNames[shiftedStart], tensorMap, context, resourceManager);\n }\n if (inputParam.type === 'tensors') {\n // TODO(mattSoulanille): This filters out NoOp nodes during execution, but\n // these should really never be in the execution graph in the first place.\n // They're necessary for ordering the graph, but should not be visible\n // during execution. Perhaps have different sets of children, one for\n // control dependencies and another for real dependencies.\n const inputs = node.inputs.slice(start, end);\n const inputNames = node.inputNames.slice(start, end)\n .filter((_name, index) => inputs[index]?.op !== 'NoOp');\n\n return inputNames.map(\n name => getTensor(name, tensorMap, context, resourceManager));\n }\n const tensor = getTensor(\n node.inputNames[shiftedStart], tensorMap, context, resourceManager);\n const data = tensor.dataSync();\n return inputParam.type === 'number' ?\n data[0] :\n util.toNestedArray(tensor.shape, data);\n }\n const attrParam = node.attrParams[paramName];\n return attrParam && attrParam.value;\n}\n\n/**\n * Retrieve the tensor from tensorsMap based on input name.\n * @param name Node input name\n * @param tensorsMap Tensors map keyed by the node\n * @param context contains tensors and information for running the current node.\n * @param resourceManager Optional. Contains global resources of the model.\n */\nexport function getTensor(\n name: string, tensorsMap: NamedTensorsMap, context: ExecutionContext,\n resourceManager?: ResourceManager): Tensor {\n const [nodeName, index] = parseNodeName(name, context);\n\n if (resourceManager != null) {\n const tensor = resourceManager.getHashTableHandleByName(nodeName);\n if (tensor != null) {\n return tensor;\n }\n }\n\n const contextId = context.currentContextIds.find(contextId => {\n return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];\n });\n\n return contextId !== undefined ?\n tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] :\n undefined;\n}\n\n/**\n * Retrieve the tensors based on input name for current context.\n * @param name Node input name\n * @param tensorsMap Tensors map keyed by the node\n */\nexport function getTensorsForCurrentContext(\n name: string, tensorsMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] {\n return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];\n}\n\n/**\n * Returns the node name, outputName and index from the Node input name.\n * @param inputName The input name of the node, in format of\n * node_name:output_index, i.e. MatMul:0, if the output_index is not set, it is\n * default to 0.\n * If the input name contains output name i.e. StringSplit:indices:0, it will\n * return ['StringSplit', 0, 'indices'].\n */\nexport function getNodeNameAndIndex(\n inputName: string, context?: ExecutionContext): [string, number, string] {\n const [nodeName, index, outputName] = parseNodeName(inputName, context);\n\n return [\n getNodeNameWithContextId(nodeName, context && context.currentContextId),\n index, outputName\n ];\n}\n\nfunction getNodeNameWithContextId(name: string, contextId?: string): string {\n return !!contextId ? `${name}-${contextId}` : name;\n}\n\nexport function parseNodeName(\n name: string, context?: ExecutionContext): [string, number, string?] {\n if (name === '') {\n return ['', 0, undefined];\n }\n\n const isCacheEnabled = context != null && context.parseNodeNameCache != null;\n if (isCacheEnabled) {\n const cachedResult = context.parseNodeNameCache.get(name);\n if (cachedResult != null) {\n return cachedResult;\n }\n }\n const parts = name.split(':');\n let result: [string, number, string?];\n if (parts.length === 1) {\n result = [name, 0, undefined];\n } else {\n const nodeName = parts[0];\n const outputName = parts.length === 3 ? parts[1] : undefined;\n const index = Number(parts[parts.length - 1]);\n result = [nodeName, index, outputName];\n }\n if (isCacheEnabled) {\n context.parseNodeNameCache.set(name, result);\n }\n return result;\n}\n\nexport function split(arr: number[], size: number) {\n const res = [];\n for (let i = 0; i < arr.length; i += size) {\n res.push(arr.slice(i, i + size));\n }\n return res;\n}\nexport function getPadding(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): ValueType {\n let pad = getParamValue('pad', node, tensorMap, context);\n if (pad === 'explicit') {\n // This is 1d array, we need to convert it to 2d array\n pad = getParamValue('explicitPaddings', node, tensorMap, context);\n const explicitPadding: [\n [number, number], [number, number], [number, number], [number, number]\n ] = [[0, 0], [0, 0], [0, 0], [0, 0]];\n for (let i = 0; i < 4; i++) {\n explicitPadding[i][0] = (pad as number[])[i * 2];\n explicitPadding[i][1] = (pad as number[])[i * 2 + 1];\n }\n return explicitPadding;\n }\n return pad;\n}\n\n/**\n * Reuse the tensor if it is marked as keep, otherwise clone the tensor to\n * avoid disposal. This is important for TensorArray and TensorList ops, since\n * internally they use a tensor as the id for TensorArray and TensorList, and\n * to simplify lookup, they also use Tensor.id as the key to the internal map.\n * These id tensors have been marked as kept in the backend, we need avoid clone\n * them in order to create new Tensor.id.\n * @param tensor\n */\nexport function cloneTensor(tensor: Tensor): Tensor {\n return tensor.kept ? tensor : clone(tensor);\n}\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Add',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'AddV2',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'AddN',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'BiasAdd',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sub',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'RealDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Div',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'DivNoNan',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FloorDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Mul',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Maximum',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Minimum',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Pow',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'SquaredDifference',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Mod',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FloorMod',\n 'category': 'arithmetic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Abs',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Acos',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Asin',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Atan',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Atan2',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'y',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Ceil',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ClipByValue',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'clipValueMin',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'clipValueMax',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Complex',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'real',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'imag',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ComplexAbs',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Cos',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Cosh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Elu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Exp',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Floor',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Log',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Imag',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'outputType',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Neg',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Real',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'outputType',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Prelu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'alpha',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Relu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Relu6',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Selu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sigmoid',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sin',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sinh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sqrt',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Rsqrt',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Square',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tan',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tanh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sign',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Round',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Expm1',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Log1p',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Reciprocal',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Softplus',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Asinh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Acosh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Atanh',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Erf',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LeakyRelu',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 0.2\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IsNan',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IsFinite',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IsInf',\n 'category': 'basic_math',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'EmptyTensorList',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 1,\n 'name': 'maxNumElements',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'LoopCond',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'pred',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Switch',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'pred',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Merge',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'Enter',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'frame_name',\n 'name': 'frameName',\n 'type': 'string'\n },\n {\n 'tfName': 'is_constant',\n 'name': 'isConstant',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Exit',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'NextIteration',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'size',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'tfName': 'dynamic_size',\n 'name': 'dynamicSize',\n 'type': 'bool'\n },\n {\n 'tfName': 'clear_after_read',\n 'name': 'clearAfterRead',\n 'type': 'bool'\n },\n {\n 'tfName': 'identical_element_shapes',\n 'name': 'identicalElementShapes',\n 'type': 'bool'\n },\n {\n 'tfName': 'tensor_array_name',\n 'name': 'name',\n 'type': 'string'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayWriteV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayReadV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayGatherV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayScatterV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayConcatV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'element_shape_except0',\n 'name': 'elementShapeExcept0',\n 'type': 'shape',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArraySplitV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'lengths',\n 'type': 'number[]'\n },\n {\n 'start': 3,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArraySizeV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'flowIn',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'TensorArrayCloseV3',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorArrayId',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'StatelessIf',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'cond',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'then_branch',\n 'name': 'thenBranch',\n 'type': 'func'\n },\n {\n 'tfName': 'else_branch',\n 'name': 'elseBranch',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'If',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'cond',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'then_branch',\n 'name': 'thenBranch',\n 'type': 'func'\n },\n {\n 'tfName': 'else_branch',\n 'name': 'elseBranch',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'StatelessWhile',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'cond',\n 'name': 'cond',\n 'type': 'func'\n },\n {\n 'tfName': 'body',\n 'name': 'body',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'While',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'cond',\n 'name': 'cond',\n 'type': 'func'\n },\n {\n 'tfName': 'body',\n 'name': 'body',\n 'type': 'func'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListScatter',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListScatterV2',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 3,\n 'name': 'numElements',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListGather',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListGetItem',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListSetItem',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'index',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListReserve',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 1,\n 'name': 'numElements',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListFromTensor',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListStack',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n },\n {\n 'tfName': 'num_elements',\n 'name': 'numElements',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListSplit',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'start': 2,\n 'name': 'lengths',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListConcat',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListConcatV2',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_shape',\n 'name': 'elementShape',\n 'type': 'shape'\n },\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListPopBack',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'elementShape',\n 'type': 'shape'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListPushBack',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'element_dtype',\n 'name': 'elementDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListLength',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'TensorListResize',\n 'category': 'control',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensorListId',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'AvgPool',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MaxPool',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': [],\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MaxPoolWithArgmax',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'include_batch_in_index',\n 'name': 'includeBatchInIndex',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'AvgPool3D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MaxPool3D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'ksize',\n 'name': 'kernelSize',\n 'type': 'number[]'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Conv1D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'stride',\n 'name': 'stride',\n 'type': 'number'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NWC'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'dilation',\n 'name': 'dilation',\n 'type': 'number',\n 'defaultValue': 1\n }\n ]\n },\n {\n 'tfOpName': 'Conv2D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'useCudnnOnGpu',\n 'name': 'useCudnnOnGpu',\n 'type': 'bool'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': '_FusedConv2D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_args',\n 'name': 'numArgs',\n 'type': 'number'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'use_cudnn_on_gpu',\n 'name': 'useCudnnOnGpu',\n 'type': 'bool',\n 'defaultValue': true\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'defaultValue': [\n 1,\n 1,\n 1,\n 1\n ]\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.0001\n },\n {\n 'tfName': 'leakyrelu_alpha',\n 'name': 'leakyreluAlpha',\n 'type': 'number',\n 'defaultValue': 0.2\n }\n ]\n },\n {\n 'tfOpName': 'Conv2DBackpropInput',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 2,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n },\n {\n 'start': 0,\n 'name': 'outputShape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2d',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'FusedDepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_args',\n 'name': 'numArgs',\n 'type': 'number'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'defaultValue': [\n 1,\n 1,\n 1,\n 1\n ]\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n }\n ]\n },\n {\n 'tfOpName': 'Conv3D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Dilation2D',\n 'category': 'convolution',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'filter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'strides',\n 'name': 'strides',\n 'type': 'number[]'\n },\n {\n 'tfName': 'rates',\n 'name': 'dilations',\n 'type': 'number[]'\n },\n {\n 'tfName': 'padding',\n 'name': 'pad',\n 'type': 'string'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Fill',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n },\n {\n 'start': 1,\n 'name': 'value',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'LinSpace',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'start',\n 'type': 'number'\n },\n {\n 'start': 1,\n 'name': 'stop',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'num',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'OneHot',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'depth',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'onValue',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'start': 3,\n 'name': 'offValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Ones',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'OnesLike',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'RandomStandardNormal',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'T',\n 'name': 'T',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'RandomUniform',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'minval',\n 'name': 'minval',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'maxval',\n 'name': 'maxval',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {\n 'tfName': 'T',\n 'name': 'T',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'RandomUniformInt',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'minval',\n 'name': 'minval',\n 'type': 'number'\n },\n {\n 'tfName': 'maxval',\n 'name': 'maxval',\n 'type': 'number'\n },\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Range',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'start',\n 'type': 'number'\n },\n {\n 'start': 1,\n 'name': 'stop',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'step',\n 'type': 'number',\n 'defaultValue': 0\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tidx',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'TruncatedNormal',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'means',\n 'name': 'mean',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'stddev',\n 'name': 'stdDev',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number'\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'T',\n 'name': 'T',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Zeros',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'ZerosLike',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Multinomial',\n 'category': 'creation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'logits',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'numSamples',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'seed',\n 'name': 'seed',\n 'type': 'number'\n },\n {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n },\n {\n 'tfName': 'output_dtype',\n 'name': 'output_dtype',\n 'type': 'dtype'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'NonMaxSuppressionV2',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV3',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n },\n {\n 'start': 4,\n 'name': 'scoreThreshold',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV4',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n },\n {\n 'start': 4,\n 'name': 'scoreThreshold',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'T_threshold',\n 'name': 'threshold',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'pad_to_max_output_size',\n 'name': 'padToMaxOutputSize',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV5',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scores',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'maxOutputSize',\n 'type': 'number'\n },\n {\n 'start': 3,\n 'name': 'iouThreshold',\n 'type': 'number'\n },\n {\n 'start': 4,\n 'name': 'scoreThreshold',\n 'type': 'number'\n },\n {\n 'start': 5,\n 'name': 'softNmsSigma',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'Where',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'condition',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ListDiff',\n 'category': 'dynamic',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'y',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'LowerBound',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sortedSequence',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'TopKV2',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'k',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'sorted',\n 'name': 'sorted',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'UpperBound',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sortedSequence',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Unique',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'UniqueV2',\n 'category': 'evaluation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'PlaceholderWithDefault',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'default',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'shape',\n 'name': 'shape',\n 'type': 'shape'\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Placeholder',\n 'category': 'graph',\n 'attrs': [\n {\n 'tfName': 'shape',\n 'name': 'shape',\n 'type': 'shape'\n },\n {\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'Const',\n 'category': 'graph'\n },\n {\n 'tfOpName': 'Identity',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'IdentityN',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'x',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'Snapshot',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Rank',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Size',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'Shape',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'ShapeN',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'x',\n 'type': 'tensors'\n }\n ]\n },\n {\n 'tfOpName': 'Print',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'data',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'message',\n 'name': 'message',\n 'type': 'string'\n },\n {\n 'tfName': 'first_n',\n 'name': 'firstN',\n 'type': 'number',\n 'notSupported': true\n },\n {\n 'tfName': 'summarize',\n 'name': 'summarize',\n 'type': 'number',\n 'defaultValue': 3\n }\n ]\n },\n {\n 'tfOpName': 'NoOp',\n 'category': 'graph',\n 'inputs': []\n },\n {\n 'tfOpName': 'StopGradient',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'FakeQuantWithMinMaxVars',\n 'category': 'graph',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'min',\n 'name': 'min',\n 'type': 'number'\n },\n {\n 'tfName': 'max',\n 'name': 'max',\n 'type': 'number'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'HashTable',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {\n 'tfName': 'shared_name',\n 'name': 'sharedName',\n 'type': 'string'\n },\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {\n 'tfName': 'key_dtype',\n 'name': 'keyDType',\n 'type': 'dtype'\n },\n {\n 'tfName': 'value_dtype',\n 'name': 'valueDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'HashTableV2',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {\n 'tfName': 'shared_name',\n 'name': 'sharedName',\n 'type': 'string'\n },\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {\n 'tfName': 'key_dtype',\n 'name': 'keyDType',\n 'type': 'dtype'\n },\n {\n 'tfName': 'value_dtype',\n 'name': 'valueDType',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableImport',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableImportV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableFind',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableFindV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'Tin',\n 'name': 'tIn',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableSize',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableSizeV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'InitializeTable',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'InitializeTableV2',\n 'category': 'hash_table',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tableHandle',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'keys',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'ResizeBilinear',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'images',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'align_corners',\n 'name': 'alignCorners',\n 'type': 'bool'\n },\n {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'ResizeNearestNeighbor',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'images',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'align_corners',\n 'name': 'alignCorners',\n 'type': 'bool'\n },\n {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'CropAndResize',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'image',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'boxes',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'boxInd',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'cropSize',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'method',\n 'name': 'method',\n 'type': 'string'\n },\n {\n 'tfName': 'extrapolation_value',\n 'name': 'extrapolationValue',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'ImageProjectiveTransformV3',\n 'category': 'image',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'images',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'transforms',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'outputShape',\n 'type': 'number[]'\n },\n {\n 'start': 3,\n 'name': 'fillValue',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'interpolation',\n 'name': 'interpolation',\n 'type': 'string'\n },\n {\n 'tfName': 'fill_mode',\n 'name': 'fillMode',\n 'type': 'string'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Equal',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'NotEqual',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Greater',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'GreaterEqual',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Less',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LessEqual',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LogicalAnd',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LogicalNot',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LogicalOr',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Select',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'condition',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'SelectV2',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'condition',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'BitwiseAnd',\n 'category': 'logical',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'y',\n 'type': 'tensor'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': '_FusedMatMul',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'end': 0,\n 'name': 'args',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_args',\n 'name': 'numArgs',\n 'type': 'number'\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.0001\n },\n {\n 'tfName': 'transpose_a',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'transpose_b',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'leakyrelu_alpha',\n 'name': 'leakyreluAlpha',\n 'type': 'number',\n 'defaultValue': 0.2\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'MatMul',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'transpose_a',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'transpose_b',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'BatchMatMul',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'adj_x',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'adj_y',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'BatchMatMulV2',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'b',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'adj_x',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'adj_y',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Transpose',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'perm',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Einsum',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'equation',\n 'name': 'equation',\n 'type': 'string'\n },\n {\n 'tfName': 'N',\n 'name': 'n',\n 'type': 'number',\n 'defaultValue': 2\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'MatrixBandPart',\n 'category': 'matrices',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'a',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'numLower',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'numUpper',\n 'type': 'tensor'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'EuclideanNorm',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool',\n 'defaultValue': false\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNorm',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scale',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'offset',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'mean',\n 'type': 'tensor'\n },\n {\n 'start': 4,\n 'name': 'variance',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNormV2',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scale',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'offset',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'mean',\n 'type': 'tensor'\n },\n {\n 'start': 4,\n 'name': 'variance',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNormV3',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'scale',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'offset',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'mean',\n 'type': 'tensor'\n },\n {\n 'start': 4,\n 'name': 'variance',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LRN',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'depth_radius',\n 'name': 'radius',\n 'type': 'number',\n 'defaultValue': 5\n },\n {\n 'tfName': 'bias',\n 'name': 'bias',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 1\n },\n {\n 'tfName': 'beta',\n 'name': 'beta',\n 'type': 'number',\n 'defaultValue': 0.5\n }\n ]\n },\n {\n 'tfOpName': 'Softmax',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'LogSoftmax',\n 'category': 'normalization',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Bincount',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'weights',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'DenseBincount',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'size',\n 'type': 'number'\n },\n {\n 'start': 2,\n 'name': 'weights',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'binary_output',\n 'name': 'binaryOutput',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Max',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Mean',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Min',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Sum',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'All',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Any',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'ArgMax',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'ArgMin',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool'\n },\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Cumprod',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'exclusive',\n 'name': 'exclusive',\n 'type': 'bool'\n },\n {\n 'tfName': 'reverse',\n 'name': 'reverse',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'Cumsum',\n 'category': 'reduction',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'exclusive',\n 'name': 'exclusive',\n 'type': 'bool'\n },\n {\n 'tfName': 'reverse',\n 'name': 'reverse',\n 'type': 'bool'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'ConcatV2',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'end': -1,\n 'name': 'tensors',\n 'type': 'tensors'\n },\n {\n 'start': -1,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'N',\n 'name': 'n',\n 'type': 'number',\n 'defaultValue': 2\n }\n ]\n },\n {\n 'tfOpName': 'Concat',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 1,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n },\n {\n 'start': 0,\n 'name': 'axis',\n 'type': 'number'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'N',\n 'name': 'n',\n 'type': 'number',\n 'defaultValue': 2\n }\n ]\n },\n {\n 'tfOpName': 'GatherV2',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n }\n ],\n 'attrs': [\n {\n 'tfName': 'batch_dims',\n 'name': 'batchDims',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Gather',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Reverse',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'dims',\n 'type': 'bool[]'\n }\n ]\n },\n {\n 'tfOpName': 'ReverseV2',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Slice',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'begin',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'size',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'StridedSlice',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'begin',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'end',\n 'type': 'number[]'\n },\n {\n 'start': 3,\n 'name': 'strides',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'begin_mask',\n 'name': 'beginMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'end_mask',\n 'name': 'endMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'new_axis_mask',\n 'name': 'newAxisMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'ellipsis_mask',\n 'name': 'ellipsisMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'shrink_axis_mask',\n 'name': 'shrinkAxisMask',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Pack',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'end': 0,\n 'name': 'tensors',\n 'type': 'tensors'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Unpack',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'num',\n 'name': 'num',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tile',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'reps',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Split',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'start': 1,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_split',\n 'name': 'numOrSizeSplits',\n 'type': 'number',\n 'defaultValue': 1\n }\n ]\n },\n {\n 'tfOpName': 'SplitV',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'numOrSizeSplits',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'axis',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'ScatterNd',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'GatherNd',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'sparseIndices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'outputShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'sparseValues',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': false,\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorScatterUpdate',\n 'category': 'slice_join',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'tensor',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'values',\n 'type': 'tensor'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'SparseFillEmptyRows',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'values',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'denseShape',\n 'type': 'tensor'\n },\n {\n 'start': 3,\n 'name': 'defaultValue',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseReshape',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'inputIndices',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'inputShape',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'newShape',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'SparseSegmentMean',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'segmentIds',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'SparseSegmentSum',\n 'category': 'sparse',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'indices',\n 'type': 'tensor'\n },\n {\n 'start': 2,\n 'name': 'segmentIds',\n 'type': 'tensor'\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'FFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'IFFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ]\n },\n {\n 'tfOpName': 'RFFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IRFFT',\n 'category': 'spectral',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n }\n];\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'StaticRegexReplace',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'pattern',\n 'name': 'pattern',\n 'type': 'string'\n },\n {\n 'tfName': 'rewrite',\n 'name': 'rewrite',\n 'type': 'string'\n },\n {\n 'tfName': 'replace_global',\n 'name': 'replaceGlobal',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'StringNGrams',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'data',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'dataSplits',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'separator',\n 'name': 'separator',\n 'type': 'string'\n },\n {\n 'tfName': 'ngram_widths',\n 'name': 'nGramWidths',\n 'type': 'number[]'\n },\n {\n 'tfName': 'left_pad',\n 'name': 'leftPad',\n 'type': 'string'\n },\n {\n 'tfName': 'right_pad',\n 'name': 'rightPad',\n 'type': 'string'\n },\n {\n 'tfName': 'pad_width',\n 'name': 'padWidth',\n 'type': 'number'\n },\n {\n 'tfName': 'preserve_short_sequences',\n 'name': 'preserveShortSequences',\n 'type': 'bool'\n }\n ],\n 'outputs': [\n 'ngrams',\n 'ngrams_splits'\n ]\n },\n {\n 'tfOpName': 'StringSplit',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'delimiter',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'skip_empty',\n 'name': 'skipEmpty',\n 'type': 'bool'\n }\n ],\n 'outputs': [\n 'indices',\n 'values',\n 'shape'\n ]\n },\n {\n 'tfOpName': 'StringToHashBucketFast',\n 'category': 'string',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'input',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'num_buckets',\n 'name': 'numBuckets',\n 'type': 'number'\n }\n ]\n }\n]\n;\n","\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Cast',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'SrcT',\n 'name': 'sdtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'DstT',\n 'name': 'dtype',\n 'type': 'dtype'\n }\n ]\n },\n {\n 'tfOpName': 'ExpandDims',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'axis',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'MirrorPad',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'padding',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'mode',\n 'name': 'mode',\n 'type': 'string'\n }\n ]\n },\n {\n 'tfOpName': 'Pad',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'padding',\n 'type': 'number[]'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'constant_value',\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'PadV2',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'padding',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Reshape',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'EnsureShape',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'Squeeze',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'tfDeprecatedName': 'squeeze_dims',\n 'name': 'axis',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'SpaceToBatchND',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'blockShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'paddings',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'BatchToSpaceND',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'blockShape',\n 'type': 'number[]'\n },\n {\n 'start': 2,\n 'name': 'crops',\n 'type': 'number[]'\n }\n ]\n },\n {\n 'tfOpName': 'DepthToSpace',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n }\n ],\n 'attrs': [\n {\n 'tfName': 'block_size',\n 'name': 'blockSize',\n 'type': 'number'\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string'\n }\n ]\n },\n {\n 'tfOpName': 'BroadcastTo',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 'x',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 'shape',\n 'type': 'number[]'\n }\n ],\n 'attrs': []\n },\n {\n 'tfOpName': 'BroadcastArgs',\n 'category': 'transformation',\n 'inputs': [\n {\n 'start': 0,\n 'name': 's0',\n 'type': 'tensor'\n },\n {\n 'start': 1,\n 'name': 's1',\n 'type': 'tensor'\n }\n ],\n 'attrs': []\n }\n]\n;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, env} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\n\nimport {getRegisteredOp} from './custom_op/register';\nimport {getNodeNameAndIndex} from './executors/utils';\nimport * as arithmetic from './op_list/arithmetic';\nimport * as basicMath from './op_list/basic_math';\nimport * as control from './op_list/control';\nimport * as convolution from './op_list/convolution';\nimport * as creation from './op_list/creation';\nimport * as dynamic from './op_list/dynamic';\nimport * as evaluation from './op_list/evaluation';\nimport * as graph from './op_list/graph';\nimport * as hashTable from './op_list/hash_table';\nimport * as image from './op_list/image';\nimport * as logical from './op_list/logical';\nimport * as matrices from './op_list/matrices';\nimport * as normalization from './op_list/normalization';\nimport * as reduction from './op_list/reduction';\nimport * as sliceJoin from './op_list/slice_join';\nimport * as sparse from './op_list/sparse';\nimport * as spectral from './op_list/spectral';\nimport * as string from './op_list/string';\nimport * as transformation from './op_list/transformation';\nimport {Graph, InputParamValue, Node, OpMapper, ParamValue} from './types';\n\nexport class OperationMapper {\n private static _instance: OperationMapper;\n\n private opMappers: {[key: string]: OpMapper};\n\n // Singleton instance for the mapper\n public static get Instance() {\n return this._instance || (this._instance = new this());\n }\n\n // Loads the op mapping from the JSON file.\n private constructor() {\n const ops = [\n arithmetic, basicMath, control, convolution, creation, dynamic,\n evaluation, graph, hashTable, image, logical, matrices, normalization,\n reduction, sliceJoin, sparse, spectral, string, transformation\n ];\n const mappersJson: OpMapper[] = [].concat(...ops.map(op => op.json));\n\n this.opMappers = mappersJson.reduce<{[key: string]: OpMapper}>(\n (map, mapper: OpMapper) => {\n map[mapper.tfOpName] = mapper;\n return map;\n },\n {});\n }\n\n // Converts the model inference graph from Tensorflow GraphDef to local\n // representation for TensorFlow.js API\n transformGraph(\n graph: tensorflow.IGraphDef,\n signature: tensorflow.ISignatureDef = {}): Graph {\n const tfNodes = graph.node;\n const placeholders: Node[] = [];\n const weights: Node[] = [];\n const initNodes: Node[] = [];\n const nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n map[node.name] = this.mapNode(node);\n if (node.op.startsWith('Placeholder')) {\n placeholders.push(map[node.name]);\n } else if (node.op === 'Const') {\n weights.push(map[node.name]);\n } else if (node.input == null || node.input.length === 0) {\n initNodes.push(map[node.name]);\n }\n return map;\n }, {});\n\n let inputs: Node[] = [];\n const outputs: Node[] = [];\n let inputNodeNameToKey: {[key: string]: string} = {};\n let outputNodeNameToKey: {[key: string]: string} = {};\n if (signature != null) {\n inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);\n outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);\n }\n const allNodes = Object.keys(nodes);\n allNodes.forEach(key => {\n const node = nodes[key];\n node.inputNames.forEach((name, index) => {\n const [nodeName, , outputName] = getNodeNameAndIndex(name);\n const inputNode = nodes[nodeName];\n if (inputNode.outputs != null) {\n const outputIndex = inputNode.outputs.indexOf(outputName);\n if (outputIndex !== -1) {\n const inputName = `${nodeName}:${outputIndex}`;\n // update the input name to use the mapped output index directly.\n node.inputNames[index] = inputName;\n }\n }\n node.inputs.push(inputNode);\n inputNode.children.push(node);\n });\n });\n\n // if signature has not outputs set, add any node that does not have\n // outputs.\n if (Object.keys(outputNodeNameToKey).length === 0) {\n allNodes.forEach(key => {\n const node = nodes[key];\n if (node.children.length === 0) {\n outputs.push(node);\n }\n });\n } else {\n Object.keys(outputNodeNameToKey).forEach(name => {\n const [nodeName, ] = getNodeNameAndIndex(name);\n const node = nodes[nodeName];\n if (node != null) {\n node.signatureKey = outputNodeNameToKey[name];\n outputs.push(node);\n }\n });\n }\n\n if (Object.keys(inputNodeNameToKey).length > 0) {\n Object.keys(inputNodeNameToKey).forEach(name => {\n const [nodeName, ] = getNodeNameAndIndex(name);\n const node = nodes[nodeName];\n if (node) {\n node.signatureKey = inputNodeNameToKey[name];\n inputs.push(node);\n }\n });\n } else {\n inputs = placeholders;\n }\n\n let functions = {};\n if (graph.library != null && graph.library.function != null) {\n functions = graph.library.function.reduce((functions, func) => {\n functions[func.signature.name] = this.mapFunction(func);\n return functions;\n }, {} as {[key: string]: Graph});\n }\n\n const result: Graph =\n {nodes, inputs, outputs, weights, placeholders, signature, functions};\n\n if (initNodes.length > 0) {\n result.initNodes = initNodes;\n }\n\n return result;\n }\n\n private mapSignatureEntries(entries: {[k: string]: tensorflow.ITensorInfo}) {\n return Object.keys(entries || {})\n .reduce<{[key: string]: string}>((prev, curr) => {\n prev[entries[curr].name] = curr;\n return prev;\n }, {});\n }\n\n private mapNode(node: tensorflow.INodeDef): Node {\n // Unsupported ops will cause an error at run-time (not parse time), since\n // they may not be used by the actual execution subgraph.\n const mapper =\n getRegisteredOp(node.op) || this.opMappers[node.op] || {} as OpMapper;\n if (node.attr == null) {\n node.attr = {};\n }\n\n const newNode: Node = {\n name: node.name,\n op: node.op,\n category: mapper.category,\n inputNames:\n (node.input ||\n []).map(input => input.startsWith('^') ? input.slice(1) : input),\n inputs: [],\n children: [],\n inputParams: {},\n attrParams: {},\n rawAttrs: node.attr,\n outputs: mapper.outputs\n };\n\n if (mapper.inputs != null) {\n newNode.inputParams =\n mapper.inputs.reduce<{[key: string]: InputParamValue}>(\n (map, param) => {\n map[param.name] = {\n type: param.type,\n inputIndexStart: param.start,\n inputIndexEnd: param.end\n };\n return map;\n },\n {});\n }\n if (mapper.attrs != null) {\n newNode.attrParams =\n mapper.attrs.reduce<{[key: string]: ParamValue}>((map, param) => {\n const type = param.type;\n let value = undefined;\n switch (param.type) {\n case 'string':\n value = getStringParam(\n node.attr, param.tfName, param.defaultValue as string);\n\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getStringParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string);\n }\n break;\n case 'string[]':\n value = getStringArrayParam(\n node.attr, param.tfName, param.defaultValue as string[]);\n\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getStringArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string[]);\n }\n break;\n case 'number':\n value = getNumberParam(\n node.attr, param.tfName,\n (param.defaultValue || 0) as number);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getNumberParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number);\n }\n break;\n case 'number[]':\n value = getNumericArrayParam(\n node.attr, param.tfName, param.defaultValue as number[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getNumericArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[]);\n }\n break;\n case 'bool':\n value = getBoolParam(\n node.attr, param.tfName, param.defaultValue as boolean);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getBoolParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as boolean);\n }\n break;\n case 'bool[]':\n value = getBoolArrayParam(\n node.attr, param.tfName, param.defaultValue as boolean[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getBoolArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as boolean[]);\n }\n break;\n case 'shape':\n value = getTensorShapeParam(\n node.attr, param.tfName, param.defaultValue as number[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getTensorShapeParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[]);\n }\n break;\n case 'shape[]':\n value = getTensorShapeArrayParam(\n node.attr, param.tfName, param.defaultValue as number[][]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getTensorShapeArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[][]);\n }\n break;\n case 'dtype':\n value = getDtypeParam(\n node.attr, param.tfName, param.defaultValue as DataType);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getDtypeParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as DataType);\n }\n break;\n case 'dtype[]':\n value = getDtypeArrayParam(\n node.attr, param.tfName, param.defaultValue as DataType[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getDtypeArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as DataType[]);\n }\n break;\n case 'func':\n value = getFuncParam(\n node.attr, param.tfName, param.defaultValue as string);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getFuncParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string);\n }\n break;\n case 'tensor':\n case 'tensors':\n break;\n default:\n throw new Error(\n `Unsupported param type: ${param.type} for op: ${node.op}`);\n }\n map[param.name] = {value, type};\n return map;\n }, {});\n }\n return newNode;\n }\n\n // map the TFunctionDef to TFJS graph object\n private mapFunction(functionDef: tensorflow.IFunctionDef): Graph {\n const tfNodes = functionDef.nodeDef;\n const placeholders: Node[] = [];\n const weights: Node[] = [];\n let nodes: {[key: string]: Node} = {};\n if (tfNodes != null) {\n nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n map[node.name] = this.mapNode(node);\n if (node.op === 'Const') {\n weights.push(map[node.name]);\n }\n return map;\n }, {});\n }\n const inputs: Node[] = [];\n const outputs: Node[] = [];\n\n functionDef.signature.inputArg.forEach(arg => {\n const [nodeName, ] = getNodeNameAndIndex(arg.name);\n const node: Node = {\n name: nodeName,\n op: 'Placeholder',\n inputs: [],\n inputNames: [],\n category: 'graph',\n inputParams: {},\n attrParams: {dtype: {value: parseDtypeParam(arg.type), type: 'dtype'}},\n children: []\n };\n node.signatureKey = arg.name;\n inputs.push(node);\n nodes[nodeName] = node;\n });\n\n const allNodes = Object.keys(nodes);\n allNodes.forEach(key => {\n const node = nodes[key];\n node.inputNames.forEach((name, index) => {\n const [nodeName, , outputName] = getNodeNameAndIndex(name);\n const inputNode = nodes[nodeName];\n if (inputNode.outputs != null) {\n const outputIndex = inputNode.outputs.indexOf(outputName);\n if (outputIndex !== -1) {\n const inputName = `${nodeName}:${outputIndex}`;\n // update the input name to use the mapped output index directly.\n node.inputNames[index] = inputName;\n }\n }\n node.inputs.push(inputNode);\n inputNode.children.push(node);\n });\n });\n\n const returnNodeMap = functionDef.ret;\n\n functionDef.signature.outputArg.forEach(output => {\n const [nodeName, index] = getNodeNameAndIndex(returnNodeMap[output.name]);\n const node = nodes[nodeName];\n if (node != null) {\n node.defaultOutput = index;\n outputs.push(node);\n }\n });\n\n const signature = this.mapArgsToSignature(functionDef);\n return {nodes, inputs, outputs, weights, placeholders, signature};\n }\n\n private mapArgsToSignature(functionDef: tensorflow.IFunctionDef):\n tensorflow.ISignatureDef {\n return {\n methodName: functionDef.signature.name,\n inputs: functionDef.signature.inputArg.reduce(\n (map, arg) => {\n map[arg.name] = this.mapArgToTensorInfo(arg);\n return map;\n },\n {} as {[key: string]: tensorflow.ITensorInfo}),\n outputs: functionDef.signature.outputArg.reduce(\n (map, arg) => {\n map[arg.name] = this.mapArgToTensorInfo(arg, functionDef.ret);\n return map;\n },\n {} as {[key: string]: tensorflow.ITensorInfo}),\n };\n }\n\n private mapArgToTensorInfo(\n arg: tensorflow.OpDef.IArgDef,\n nameMap?: {[key: string]: string}): tensorflow.ITensorInfo {\n let name = arg.name;\n if (nameMap != null) {\n name = nameMap[name];\n }\n return {name, dtype: arg.type};\n }\n}\n\nexport function decodeBase64(text: string): string {\n const global = env().global;\n if (typeof global.atob !== 'undefined') {\n return global.atob(text);\n } else if (typeof Buffer !== 'undefined') {\n return new Buffer(text, 'base64').toString();\n } else {\n throw new Error(\n 'Unable to decode base64 in this environment. ' +\n 'Missing built-in atob() or Buffer()');\n }\n}\n\nexport function parseStringParam(s: []|string, keepCase: boolean): string {\n const value =\n Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);\n return keepCase ? value : value.toLowerCase();\n}\n\nexport function getStringParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string,\n keepCase = false): string {\n const param = attrs[name];\n if (param != null) {\n return parseStringParam(param.s, keepCase);\n }\n return def;\n}\n\nexport function getBoolParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: boolean): boolean {\n const param = attrs[name];\n return param ? param.b : def;\n}\n\nexport function getNumberParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number): number {\n const param = attrs[name] || {};\n const value =\n param['i'] != null ? param['i'] : (param['f'] != null ? param['f'] : def);\n return (typeof value === 'number') ? value : parseInt(value, 10);\n}\n\nexport function parseDtypeParam(value: string|tensorflow.DataType): DataType {\n if (typeof (value) === 'string') {\n // tslint:disable-next-line:no-any\n value = tensorflow.DataType[value as any];\n }\n switch (value) {\n case tensorflow.DataType.DT_FLOAT:\n case tensorflow.DataType.DT_HALF:\n return 'float32';\n case tensorflow.DataType.DT_INT32:\n case tensorflow.DataType.DT_INT64:\n case tensorflow.DataType.DT_INT8:\n case tensorflow.DataType.DT_UINT8:\n return 'int32';\n case tensorflow.DataType.DT_BOOL:\n return 'bool';\n case tensorflow.DataType.DT_DOUBLE:\n return 'float32';\n case tensorflow.DataType.DT_STRING:\n return 'string';\n case tensorflow.DataType.DT_COMPLEX64:\n case tensorflow.DataType.DT_COMPLEX128:\n return 'complex64';\n default:\n // Unknown dtype error will happen at runtime (instead of parse time),\n // since these nodes might not be used by the actual subgraph execution.\n return null;\n }\n}\n\nexport function getFuncParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: string): string {\n const param = attrs[name];\n if (param && param.func) {\n return param.func.name;\n }\n return def;\n}\n\nexport function getDtypeParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: DataType): DataType {\n const param = attrs[name];\n if (param && param.type) {\n return parseDtypeParam(param.type);\n }\n return def;\n}\n\nexport function getDtypeArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: DataType[]): DataType[] {\n const param = attrs[name];\n if (param && param.list && param.list.type) {\n return param.list.type.map(v => parseDtypeParam(v));\n }\n return def;\n}\n\nexport function parseTensorShapeParam(shape: tensorflow.ITensorShape): number[]|\n undefined {\n if (shape.unknownRank) {\n return undefined;\n }\n if (shape.dim != null) {\n return shape.dim.map(\n dim =>\n (typeof dim.size === 'number') ? dim.size : parseInt(dim.size, 10));\n }\n return [];\n}\n\nexport function getTensorShapeParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def?: number[]): number[]|undefined {\n const param = attrs[name];\n if (param && param.shape) {\n return parseTensorShapeParam(param.shape);\n }\n return def;\n}\n\nexport function getNumericArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number[]): number[] {\n const param = attrs[name];\n if (param) {\n return ((param.list.f && param.list.f.length ? param.list.f :\n param.list.i) ||\n [])\n .map(v => (typeof v === 'number') ? v : parseInt(v, 10));\n }\n return def;\n}\n\nexport function getStringArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string[],\n keepCase = false): string[] {\n const param = attrs[name];\n if (param && param.list && param.list.s) {\n return param.list.s.map((v) => {\n return parseStringParam(v, keepCase);\n });\n }\n return def;\n}\n\nexport function getTensorShapeArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number[][]): number[][] {\n const param = attrs[name];\n if (param && param.list && param.list.shape) {\n return param.list.shape.map((v) => {\n return parseTensorShapeParam(v);\n });\n }\n return def;\n}\n\nexport function getBoolArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: boolean[]): boolean[] {\n const param = attrs[name];\n if (param && param.list && param.list.b) {\n return param.list.b;\n }\n return def;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {getTensor} from '../executors/utils';\nimport {getBoolArrayParam, getBoolParam, getDtypeArrayParam, getDtypeParam, getNumberParam, getNumericArrayParam, getStringArrayParam, getStringParam, getTensorShapeArrayParam, getTensorShapeParam} from '../operation_mapper';\nimport {GraphNode, Node, ValueType} from '../types';\n\n/**\n * Helper class for lookup inputs and params for nodes in the model graph.\n */\nexport class NodeValueImpl implements GraphNode {\n public readonly inputs: Tensor[] = [];\n public readonly attrs: {[key: string]: ValueType} = {};\n constructor(\n private node: Node, private tensorMap: NamedTensorsMap,\n private context: ExecutionContext) {\n this.inputs = node.inputNames.map(name => this.getInput(name));\n if (node.rawAttrs != null) {\n this.attrs = Object.keys(node.rawAttrs)\n .reduce((attrs: {[key: string]: ValueType}, key) => {\n attrs[key] = this.getAttr(key);\n return attrs;\n }, {});\n }\n }\n\n /**\n * Return the value of the attribute or input param.\n * @param name String: name of attribute or input param.\n */\n private getInput(name: string): Tensor {\n return getTensor(name, this.tensorMap, this.context);\n }\n\n /**\n * Return the value of the attribute or input param.\n * @param name String: name of attribute or input param.\n */\n private getAttr(name: string, defaultValue?: ValueType): ValueType {\n const value = this.node.rawAttrs[name];\n if (value.tensor != null) {\n return getTensor(name, this.tensorMap, this.context);\n }\n if (value.i != null || value.f != null) {\n return getNumberParam(this.node.rawAttrs, name, defaultValue as number);\n }\n if (value.s != null) {\n return getStringParam(this.node.rawAttrs, name, defaultValue as string);\n }\n if (value.b != null) {\n return getBoolParam(this.node.rawAttrs, name, defaultValue as boolean);\n }\n if (value.shape != null) {\n return getTensorShapeParam(\n this.node.rawAttrs, name, defaultValue as number[]);\n }\n if (value.type != null) {\n return getDtypeParam(this.node.rawAttrs, name, defaultValue as DataType);\n }\n if (value.list != null) {\n if (value.list.i != null || value.list.f != null) {\n return getNumericArrayParam(\n this.node.rawAttrs, name, defaultValue as number[]);\n }\n if (value.list.s != null) {\n return getStringArrayParam(\n this.node.rawAttrs, name, defaultValue as string[]);\n }\n if (value.list.shape != null) {\n return getTensorShapeArrayParam(\n this.node.rawAttrs, name, defaultValue as number[][]);\n }\n if (value.list.b != null) {\n return getBoolArrayParam(\n this.node.rawAttrs, name, defaultValue as boolean[]);\n }\n if (value.list.type != null) {\n return getDtypeArrayParam(\n this.node.rawAttrs, name, defaultValue as DataType[]);\n }\n }\n\n return defaultValue;\n }\n}\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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) {\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) {\n this.tensors.forEach(tensor => {\n if (keepIds == null || !keepIds.has(tensor.id)) {\n tensor.dispose();\n }\n });\n this.tensors.length = 0;\n this.idTensor.dispose();\n }\n /**\n * The size of the tensors in the tensor list.\n */\n size() {\n return this.tensors.length;\n }\n\n /**\n * Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)\n * tf.Tensor.\n * @param elementShape shape of each tensor\n * @param elementDtype data type of each tensor\n * @param numElements the number of elements to stack\n */\n stack(elementShape: number[], elementDtype: DataType, numElements = -1):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n if (numElements !== -1 && this.tensors.length !== numElements) {\n throw new Error(`Operation expected a list with ${\n numElements} elements but got a list with ${\n this.tensors.length} elements.`);\n }\n assertShapesMatchAllowUndefinedSize(\n elementShape, this.elementShape, 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n return tidy(() => {\n const reshapedTensors =\n this.tensors.map(tensor => reshape(tensor, outputElementShape));\n return stack(reshapedTensors, 0);\n });\n }\n\n /**\n * Pop a tensor from the end of the list.\n * @param elementShape shape of the tensor\n * @param elementDtype data type of the tensor\n */\n popBack(elementShape: number[], elementDtype: DataType): Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n\n if (this.size() === 0) {\n throw new Error('Trying to pop from an empty list.');\n }\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n const tensor = this.tensors.pop();\n tensor.kept = false;\n\n assertShapesMatchAllowUndefinedSize(\n tensor.shape, elementShape, 'TensorList shape mismatch: ');\n\n return reshape(tensor, outputElementShape);\n }\n\n /**\n * Push a tensor to the end of the list.\n * @param tensor Tensor to be pushed.\n */\n pushBack(tensor: Tensor) {\n if (tensor.dtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${this.elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n tensor.shape, this.elementShape, 'TensorList shape mismatch: ');\n\n if (this.maxNumElements === this.size()) {\n throw new Error(`Trying to push element into a full list.`);\n }\n keep(tensor);\n this.tensors.push(tensor);\n }\n\n /**\n * Update the size of the list.\n * @param size the new size of the list.\n */\n resize(size: number) {\n if (size < 0) {\n throw new Error(\n `TensorListResize expects size to be non-negative. Got: ${size}`);\n }\n\n if (this.maxNumElements !== -1 && size > this.maxNumElements) {\n throw new Error(`TensorListResize input size ${\n size} is greater maxNumElement ${this.maxNumElements}.`);\n }\n\n const destTensorList: TensorList = new TensorList(\n [], this.elementShape, this.elementDtype, this.maxNumElements);\n destTensorList.tensors.length = size;\n for (let i = 0; i < Math.min(this.tensors.length, size); ++i) {\n destTensorList.tensors[i] = this.tensors[i];\n }\n return destTensorList;\n }\n\n /**\n * Retrieve the element at the provided index\n * @param elementShape shape of the tensor\n * @param elementDtype dtype of the tensor\n * @param elementIndex index of the tensor\n */\n getItem(elementIndex: number, elementShape: number[], elementDtype: DataType):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n if (elementIndex < 0 || elementIndex > this.tensors.length) {\n throw new Error(`Trying to access element ${\n elementIndex} in a list with ${this.tensors.length} elements.`);\n }\n\n if (this.tensors[elementIndex] == null) {\n throw new Error(`element at index ${elementIndex} is null.`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.tensors[elementIndex].shape, elementShape,\n 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n return reshape(this.tensors[elementIndex], outputElementShape);\n }\n\n /**\n * Set the tensor at the index\n * @param elementIndex index of the tensor\n * @param tensor the tensor to be inserted into the list\n */\n setItem(elementIndex: number, tensor: Tensor) {\n if (tensor.dtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${this.elementDtype}`);\n }\n\n if (elementIndex < 0 ||\n this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {\n throw new Error(`Trying to set element ${\n elementIndex} in a list with max ${this.maxNumElements} elements.`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, tensor.shape, 'TensorList shape mismatch: ');\n keep(tensor);\n\n // dispose the previous value if it is replacing.\n if (this.tensors[elementIndex] != null) {\n this.tensors[elementIndex].kept = false;\n }\n\n this.tensors[elementIndex] = tensor;\n }\n\n /**\n * Return selected values in the TensorList as a stacked Tensor. All of\n * selected values must have been written and their shapes must all match.\n * @param indices indices of tensors to gather\n * @param elementDtype output tensor dtype\n * @param elementShape output tensor element shape\n */\n gather(indices: number[], elementDtype: DataType, elementShape: number[]):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, elementShape, 'TensorList shape mismatch: ');\n\n // When indices is greater than the size of the list, indices beyond the\n // size of the list are ignored.\n indices = indices.slice(0, this.size());\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n if (indices.length === 0) {\n return tensor([], [0].concat(outputElementShape));\n }\n\n return tidy(() => {\n const tensors =\n indices.map(i => reshape(this.tensors[i], outputElementShape));\n return stack(tensors, 0);\n });\n }\n\n /**\n * Return the values in the TensorList as a concatenated Tensor.\n * @param elementDtype output tensor dtype\n * @param elementShape output tensor element shape\n */\n concat(elementDtype: DataType, elementShape: number[]): Tensor {\n if (!!elementDtype && elementDtype !== this.elementDtype) {\n throw new Error(`TensorList dtype is ${\n this.elementDtype} but concat requested dtype ${elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, elementShape, 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n\n if (this.size() === 0) {\n return tensor([], [0].concat(outputElementShape));\n }\n return tidy(() => {\n const tensors = this.tensors.map(t => reshape(t, outputElementShape));\n return concat(tensors, 0);\n });\n }\n}\n\n/**\n * Creates a TensorList which, when stacked, has the value of tensor.\n * @param tensor from tensor\n * @param elementShape output tensor element shape\n */\nexport function fromTensor(\n tensor: Tensor, elementShape: number[], elementDtype: DataType) {\n const dtype = tensor.dtype;\n if (tensor.shape.length < 1) {\n throw new Error(\n `Tensor must be at least a vector, but saw shape: ${tensor.shape}`);\n }\n if (tensor.dtype !== elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${elementDtype}`);\n }\n const tensorElementShape = tensor.shape.slice(1);\n assertShapesMatchAllowUndefinedSize(\n tensorElementShape, elementShape, 'TensorList shape mismatch: ');\n const tensorList: Tensor[] = unstack(tensor);\n return new TensorList(tensorList, elementShape, dtype);\n}\n\n/**\n * Return a TensorList of the given size with empty elements.\n * @param elementShape the shape of the future elements of the list\n * @param elementDtype the desired type of elements in the list\n * @param numElements the number of elements to reserve\n * @param maxNumElements the maximum number of elements in th list\n */\nexport function reserve(\n elementShape: number[], elementDtype: DataType, numElements: number,\n maxNumElements: number) {\n return new TensorList([], elementShape, elementDtype, maxNumElements);\n}\n\n/**\n * Put tensors at specific indices of a stacked tensor into a TensorList.\n * @param indices list of indices on how to scatter the tensor.\n * @param tensor input tensor.\n * @param elementShape the shape of the future elements of the list\n * @param numElements the number of elements to scatter\n */\nexport function scatter(\n tensor: Tensor, indices: number[], elementShape: number[],\n numElements?: number): TensorList {\n if (indices.length !== tensor.shape[0]) {\n throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${\n indices.length} vs. ${tensor.shape[0]}`);\n }\n\n const maxIndex = Math.max(...indices);\n\n if (numElements != null && numElements !== -1 && maxIndex >= numElements) {\n throw new Error(\n `Max index must be < array size (${maxIndex} vs. ${numElements})`);\n }\n\n const list = new TensorList([], elementShape, tensor.dtype, numElements);\n const tensors = unstack(tensor, 0);\n indices.forEach((value, index) => {\n list.setItem(value, tensors[index]);\n });\n return list;\n}\n\n/**\n * Split the values of a Tensor into a TensorList.\n * @param length the lengths to use when splitting value along\n * its first dimension.\n * @param tensor the tensor to split.\n * @param elementShape the shape of the future elements of the list\n */\nexport function split(\n tensor: Tensor, length: number[], elementShape: number[]) {\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n\n const shapeWithoutFirstDim = tensor.shape.slice(1);\n const outputElementShape =\n mergeElementShape(shapeWithoutFirstDim, elementShape);\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors: Tensor[] = tidy(() => {\n const tensors = [];\n tensor = reshape(tensor, [1, totalLength, elementPerRow]);\n for (let i = 0; i < length.length; ++i) {\n const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = reshape(\n slice(tensor, indices, sizes), outputElementShape as number[]);\n }\n tensor.dispose();\n return tensors;\n });\n\n const list = new TensorList([], elementShape, tensor.dtype, length.length);\n\n for (let i = 0; i < tensors.length; i++) {\n list.setItem(i, tensors[i]);\n }\n return list;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, scalar, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {TensorArray} from '../../executor/tensor_array';\nimport {fromTensor, reserve, scatter, split} from '../../executor/tensor_list';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Promise => {\n switch (node.op) {\n case 'If':\n case 'StatelessIf': {\n const thenFunc =\n getParamValue('thenBranch', node, tensorMap, context) as string;\n const elseFunc =\n getParamValue('elseBranch', node, tensorMap, context) as string;\n const cond = getParamValue('cond', node, tensorMap, context) as Tensor;\n const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n const condValue = await cond.data();\n if (condValue[0]) {\n return context.functionMap[thenFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap);\n } else {\n return context.functionMap[elseFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap);\n }\n }\n case 'While':\n case 'StatelessWhile': {\n const bodyFunc =\n getParamValue('body', node, tensorMap, context) as string;\n const condFunc =\n getParamValue('cond', node, tensorMap, context) as string;\n const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n\n // Calculate the condition of the loop\n const condResult =\n (await context.functionMap[condFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap));\n const argIds = args.map(tensor => tensor.id);\n let condValue = await condResult[0].data();\n // Dispose the intermediate tensors for condition function\n condResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n\n let result: Tensor[] = args;\n\n while (condValue[0]) {\n // Record the previous result for intermediate tensor tracking\n const origResult = result;\n // Execution the body of the loop\n result = await context.functionMap[bodyFunc].executeFunctionAsync(\n result, context.tensorArrayMap, context.tensorListMap);\n const resultIds = result.map(tensor => tensor.id);\n\n // Dispose the intermediate tensor for body function that is not global\n // kept, not input/output of the body function\n origResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n resultIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n\n // Recalcuate the condition of the loop using the latest results.\n const condResult =\n (await context.functionMap[condFunc].executeFunctionAsync(\n result, context.tensorArrayMap, context.tensorListMap));\n condValue = await condResult[0].data();\n // Dispose the intermediate tensors for condition function\n condResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n resultIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n }\n return result;\n }\n case 'LoopCond': {\n const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n return [cloneTensor(pred)];\n }\n case 'Switch': {\n const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n let data = getParamValue('data', node, tensorMap, context) as Tensor;\n if (!data.kept) {\n data = cloneTensor(data);\n }\n // Outputs nodes :0 => false, :1 => true\n return (await pred.data())[0] ? [undefined, data] : [data, undefined];\n }\n case 'Merge': {\n const inputName = node.inputNames.find(\n name => getTensor(name, tensorMap, context) !== undefined);\n if (inputName) {\n const data = getTensor(inputName, tensorMap, context);\n return [cloneTensor(data)];\n }\n return undefined;\n }\n case 'Enter': {\n const frameId =\n getParamValue('frameName', node, tensorMap, context) as string;\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.enterFrame(frameId);\n return [cloneTensor(data)];\n }\n case 'Exit': {\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.exitFrame();\n return [cloneTensor(data)];\n }\n case 'NextIteration': {\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.nextIteration();\n return [cloneTensor(data)];\n }\n case 'TensorArrayV3': {\n const size = getParamValue('size', node, tensorMap, context) as number;\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const dynamicSize =\n getParamValue('dynamicSize', node, tensorMap, context) as boolean;\n const clearAfterRead =\n getParamValue('clearAfterRead', node, tensorMap, context) as boolean;\n const identicalElementShapes =\n getParamValue('identicalElementShapes', node, tensorMap, context) as\n boolean;\n const name = getParamValue('name', node, tensorMap, context) as string;\n const tensorArray = new TensorArray(\n name, dtype, size, elementShape, identicalElementShapes, dynamicSize,\n clearAfterRead);\n context.addTensorArray(tensorArray);\n return [tensorArray.idTensor, scalar(1.0)];\n }\n case 'TensorArrayWriteV3': {\n const id =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const index = getParamValue('index', node, tensorMap, context) as number;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const writeTensorArray = context.getTensorArray(id.id);\n writeTensorArray.write(index, writeTensor);\n return [writeTensorArray.idTensor];\n }\n case 'TensorArrayReadV3': {\n const readId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const readIndex =\n getParamValue('index', node, tensorMap, context) as number;\n const readTensorArray = context.getTensorArray(readId.id);\n return [readTensorArray.read(readIndex)];\n }\n case 'TensorArrayGatherV3': {\n const gatherId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const gatherIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const gatherDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const gatherTensorArray = context.getTensorArray(gatherId.id);\n return [gatherTensorArray.gather(gatherIndices, gatherDtype)];\n }\n case 'TensorArrayScatterV3': {\n const scatterId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const scatterIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const scatterTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const scatterTensorArray = context.getTensorArray(scatterId.id);\n scatterTensorArray.scatter(scatterIndices, scatterTensor);\n return [scatterTensorArray.idTensor];\n }\n case 'TensorArrayConcatV3': {\n const concatId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const concatTensorArray = context.getTensorArray(concatId.id);\n const concatDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n return [concatTensorArray.concat(concatDtype)];\n }\n case 'TensorArraySplitV3': {\n const splitId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const splitTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const lengths =\n getParamValue('lengths', node, tensorMap, context) as number[];\n const splitTensorArray = context.getTensorArray(splitId.id);\n splitTensorArray.split(lengths, splitTensor);\n return [splitTensorArray.idTensor];\n }\n case 'TensorArraySizeV3': {\n const sizeId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const sizeTensorArray = context.getTensorArray(sizeId.id);\n return [scalar(sizeTensorArray.size(), 'int32')];\n }\n case 'TensorArrayCloseV3': {\n const closeId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const closeTensorArray = context.getTensorArray(closeId.id);\n closeTensorArray.clearAndClose();\n return [closeTensorArray.idTensor];\n }\n case 'TensorListSetItem': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const index = getParamValue('index', node, tensorMap, context) as number;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n tensorList.setItem(index, writeTensor);\n return [tensorList.idTensor];\n }\n case 'TensorListGetItem': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const readIndex =\n getParamValue('index', node, tensorMap, context) as number;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n\n const elementDType =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.getItem(readIndex, elementShape, elementDType)];\n }\n case 'TensorListScatterV2':\n case 'TensorListScatter': {\n const scatterIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const scatterTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const numElements =\n getParamValue('numElements', node, tensorMap, context) as number;\n const tensorList =\n scatter(scatterTensor, scatterIndices, elementShape, numElements);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListReserve':\n case 'EmptyTensorList': {\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n let numElementsParam;\n\n if (node.op === 'TensorListReserve') {\n numElementsParam = 'numElements';\n } else {\n numElementsParam = 'maxNumElements';\n }\n\n const numElements =\n getParamValue(numElementsParam, node, tensorMap, context) as number;\n const maxNumElements = node.op === 'TensorListReserve' ? -1 : numElements;\n const tensorList =\n reserve(elementShape, elementDtype, numElements, maxNumElements);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListGather': {\n const gatherId =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const gatherIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(gatherId.id);\n return [tensorList.gather(gatherIndices, elementDtype, elementShape)];\n }\n case 'TensorListStack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const numElements =\n getParamValue('numElements', node, tensorMap, context) as number;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.stack(elementShape, elementDtype, numElements)];\n }\n case 'TensorListFromTensor': {\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = fromTensor(tensor, elementShape, elementDtype);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListConcat':\n case 'TensorListConcatV2': {\n const concatId =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(concatId.id);\n const concatDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n return [tensorList.concat(concatDtype, elementShape)];\n }\n case 'TensorListPushBack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n tensorList.pushBack(writeTensor);\n return [tensorList.idTensor];\n }\n case 'TensorListPopBack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDType =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.popBack(elementShape, elementDType)];\n }\n case 'TensorListSplit': {\n const splitTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const lengths =\n getParamValue('lengths', node, tensorMap, context) as number[];\n\n const tensorList = split(splitTensor, lengths, elementShape);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListLength': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n return [scalar(tensorList.size(), 'int32')];\n }\n case 'TensorListResize': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const size = getParamValue('size', node, tensorMap, context) as number;\n\n const srcTensorList = context.getTensorList(idTensor.id);\n const destTensorList = srcTensorList.resize(size);\n context.addTensorList(destTensorList);\n return [destTensorList.idTensor];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'control';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Rank, Tensor, Tensor3D, Tensor4D, Tensor5D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getPadding, getParamValue} from './utils';\n\nfunction fusedConvAndDepthWiseParams(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n const [extraOp, activationFunc] =\n (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n const isBiasAdd = extraOp === 'biasadd';\n const noBiasAdd = !isBiasAdd;\n const isPrelu = activationFunc === 'prelu';\n const isBatchNorm = extraOp === 'fusedbatchnorm';\n\n const numArgs =\n (getParamValue('numArgs', node, tensorMap, context) as number);\n if (isBiasAdd) {\n if (isPrelu && numArgs !== 2) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' +\n 'must have two extra arguments: bias and alpha.');\n }\n if (!isPrelu && isBiasAdd && numArgs !== 1) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with BiasAdd must have ' +\n 'one extra argument: bias.');\n }\n }\n if (isBatchNorm) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported');\n }\n const stride = getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n let [biasArg, preluArg] =\n getParamValue('args', node, tensorMap, context) as Tensor[];\n if (noBiasAdd) {\n preluArg = biasArg;\n biasArg = undefined;\n }\n const leakyreluAlpha =\n getParamValue('leakyreluAlpha', node, tensorMap, context) as number;\n\n return {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha\n };\n}\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Conv1D': {\n const stride =\n getParamValue('stride', node, tensorMap, context) as number;\n const pad = getParamValue('pad', node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilation =\n getParamValue('dilation', node, tensorMap, context) as number;\n return [ops.conv1d(\n getParamValue('x', node, tensorMap, context) as Tensor3D,\n getParamValue('filter', node, tensorMap, context) as Tensor3D,\n stride, pad as 'valid' | 'same', dataFormat as 'NWC' | 'NCW',\n dilation)];\n }\n case 'Conv2D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n return [ops.conv2d(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n [stride[1], stride[2]], pad as 'valid' | 'same',\n dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n }\n case '_FusedConv2D': {\n const {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha\n } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n return [ops.fused.conv2d({\n x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n filter: getParamValue('filter', node, tensorMap, context) as\n Tensor4D,\n strides: [stride[1], stride[2]],\n pad: pad as 'valid' | 'same',\n dataFormat: dataFormat as 'NHWC' | 'NCHW',\n dilations: [dilations[1], dilations[2]],\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n }\n\n case 'FusedDepthwiseConv2dNative': {\n const {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha,\n } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n return [ops.fused.depthwiseConv2d({\n x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n filter: getParamValue('filter', node, tensorMap, context) as\n Tensor4D,\n strides: [stride[1], stride[2]],\n pad: pad as 'valid' | 'same',\n dataFormat: dataFormat as 'NHWC' | 'NCHW',\n dilations: [dilations[1], dilations[2]],\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n }\n case 'Conv2DBackpropInput':\n case 'Conv2dTranspose': {\n const shape = getParamValue(\n 'outputShape', node, tensorMap,\n context) as [number, number, number] |\n [number, number, number, number];\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n return [ops.conv2dTranspose(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n shape, [stride[1], stride[2]], pad as 'valid' | 'same')];\n }\n case 'DepthwiseConv2dNative':\n case 'DepthwiseConv2d': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n\n return [ops.depthwiseConv2d(\n getParamValue('input', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n [stride[1], stride[2]], pad as 'valid' | 'same',\n dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n }\n case 'Conv3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n return [ops.conv3d(\n getParamValue('x', node, tensorMap, context) as Tensor4D |\n Tensor,\n getParamValue('filter', node, tensorMap, context) as\n Tensor,\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same',\n dataFormat as 'NDHWC' | 'NCDHW',\n [dilations[1], dilations[2], dilations[3]])];\n }\n case 'AvgPool': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.avgPool(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same')];\n }\n case 'MaxPool': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.maxPool(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same')];\n }\n case 'MaxPoolWithArgmax': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n const includeBatchInIndex =\n getParamValue('includeBatchInIndex', node, tensorMap, context) as\n boolean;\n const {result, indexes} = ops.maxPoolWithArgmax(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same', includeBatchInIndex);\n return [result, indexes];\n }\n case 'AvgPool3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.avgPool3d(\n getParamValue('x', node, tensorMap, context) as Tensor5D,\n [kernelSize[1], kernelSize[2], kernelSize[3]],\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n }\n\n case 'MaxPool3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [ops.maxPool3d(\n getParamValue('x', node, tensorMap, context) as Tensor5D,\n [kernelSize[1], kernelSize[2], kernelSize[3]],\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n }\n\n case 'Dilation2D': {\n const strides =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n\n // strides: [1, stride_height, stride_width, 1].\n const strideHeight = strides[1];\n const strideWidth = strides[2];\n\n // dilations: [1, dilation_height, dilation_width, 1].\n const dilationHeight = dilations[1];\n const dilationWidth = dilations[2];\n\n return [ops.dilation2d(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor3D,\n [strideHeight, strideWidth], pad as 'valid' | 'same',\n [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)];\n }\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'convolution';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport { ResourceManager } from '../../executor/resource_manager';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nfunction nmsParams(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n const boxes = getParamValue('boxes', node, tensorMap, context) as Tensor;\n const scores = getParamValue('scores', node, tensorMap, context) as Tensor;\n const maxOutputSize =\n getParamValue('maxOutputSize', node, tensorMap, context) as number;\n const iouThreshold =\n getParamValue('iouThreshold', node, tensorMap, context) as number;\n const scoreThreshold =\n getParamValue('scoreThreshold', node, tensorMap, context) as number;\n const softNmsSigma =\n getParamValue('softNmsSigma', node, tensorMap, context) as number;\n\n return {\n boxes,\n scores,\n maxOutputSize,\n iouThreshold,\n scoreThreshold,\n softNmsSigma\n };\n}\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, resourceManager: ResourceManager,\n ops = tfOps): Promise => {\n switch (node.op) {\n case 'NonMaxSuppressionV5': {\n const {\n boxes,\n scores,\n maxOutputSize,\n iouThreshold,\n scoreThreshold,\n softNmsSigma\n } = nmsParams(node, tensorMap, context);\n\n const result = await ops.image.nonMaxSuppressionWithScoreAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold, softNmsSigma);\n\n return [result.selectedIndices, result.selectedScores];\n }\n case 'NonMaxSuppressionV4': {\n const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n nmsParams(node, tensorMap, context);\n\n const padToMaxOutputSize =\n getParamValue('padToMaxOutputSize', node, tensorMap, context) as\n boolean;\n\n const result = await ops.image.nonMaxSuppressionPaddedAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold, padToMaxOutputSize);\n\n return [result.selectedIndices, result.validOutputs];\n }\n case 'NonMaxSuppressionV3':\n case 'NonMaxSuppressionV2': {\n const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n nmsParams(node, tensorMap, context);\n\n return [await ops.image.nonMaxSuppressionAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold)];\n }\n case 'Where': {\n const condition = ops.cast(\n (getParamValue('condition', node, tensorMap, context) as Tensor),\n 'bool');\n const result = [await ops.whereAsync(condition)];\n condition.dispose();\n return result;\n }\n case 'ListDiff': {\n return ops.setdiff1dAsync(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor);\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'dynamic';\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;\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();\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 {\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 {\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../data/types';\nimport {ExecutionContext} from '../executor/execution_context';\nimport {ResourceManager} from '../executor/resource_manager';\n\nimport {NodeValueImpl} from './custom_op/node_value_impl';\nimport {getRegisteredOp} from './custom_op/register';\nimport * as arithmetic from './executors/arithmetic_executor';\nimport * as basicMath from './executors/basic_math_executor';\nimport * as control from './executors/control_executor';\nimport * as convolution from './executors/convolution_executor';\nimport * as creation from './executors/creation_executor';\nimport * as dynamic from './executors/dynamic_executor';\nimport * as evaluation from './executors/evaluation_executor';\nimport * as graph from './executors/graph_executor';\nimport * as hashTable from './executors/hash_table_executor';\nimport * as image from './executors/image_executor';\nimport * as logical from './executors/logical_executor';\nimport * as matrices from './executors/matrices_executor';\nimport * as normalization from './executors/normalization_executor';\nimport * as ragged from './executors/ragged_executor';\nimport * as reduction from './executors/reduction_executor';\nimport * as sliceJoin from './executors/slice_join_executor';\nimport * as sparse from './executors/sparse_executor';\nimport * as spectral from './executors/spectral_executor';\nimport * as string from './executors/string_executor';\nimport * as transformation from './executors/transformation_executor';\nimport {Node} from './types';\n\n/**\n * Executes the op defined by the node object.\n * @param node\n * @param tensorMap contains tensors for executed nodes and weights\n * @param context contains tensors and information for running the current node.\n * @param resourceManager Optional. Contains global resources of the model.\n */\nexport function executeOp(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n resourceManager?: ResourceManager, tidy = tfc.tidy): tfc.Tensor[]|\n Promise {\n const value =\n ((node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) => {\n switch (node.category) {\n case 'arithmetic':\n return tidy(() => arithmetic.executeOp(node, tensorMap, context));\n case 'basic_math':\n return tidy(() => basicMath.executeOp(node, tensorMap, context));\n case 'control':\n return control.executeOp(node, tensorMap, context);\n case 'convolution':\n return tidy(() => convolution.executeOp(node, tensorMap, context));\n case 'creation':\n return tidy(() => creation.executeOp(node, tensorMap, context));\n case 'dynamic':\n return dynamic.executeOp(node, tensorMap, context);\n case 'evaluation':\n return tidy(() => evaluation.executeOp(node, tensorMap, context));\n case 'image':\n return tidy(() => image.executeOp(node, tensorMap, context));\n case 'graph':\n return tidy(() => graph.executeOp(node, tensorMap, context));\n case 'logical':\n return tidy(() => logical.executeOp(node, tensorMap, context));\n case 'matrices':\n return tidy(() => matrices.executeOp(node, tensorMap, context));\n case 'normalization':\n return tidy(\n () => normalization.executeOp(node, tensorMap, context));\n case 'ragged':\n return tidy(() => ragged.executeOp(node, tensorMap, context));\n case 'reduction':\n return tidy(() => reduction.executeOp(node, tensorMap, context));\n case 'slice_join':\n return tidy(() => sliceJoin.executeOp(node, tensorMap, context));\n case 'sparse':\n return tidy(() => sparse.executeOp(node, tensorMap, context));\n case 'spectral':\n return tidy(() => spectral.executeOp(node, tensorMap, context));\n case 'string':\n return tidy(() => string.executeOp(node, tensorMap, context));\n case 'transformation':\n return tidy(\n () => transformation.executeOp(node, tensorMap, context));\n case 'hash_table':\n return hashTable.executeOp(\n node, tensorMap, context, resourceManager);\n case 'custom':\n const opMapper = getRegisteredOp(node.op);\n if (opMapper && opMapper.customExecutor) {\n return opMapper.customExecutor(\n new NodeValueImpl(node, tensorMap, context));\n } else {\n throw TypeError(`Custom op ${node.op} is not registered.`);\n }\n default:\n throw TypeError(\n `Unknown op '${node.op}'. File an issue at ` +\n `https://github.com/tensorflow/tfjs/issues so we can add it` +\n `, or register a custom execution with tf.registerOp()`);\n }\n })(node, tensorMap, context);\n if (tfc.util.isPromise(value)) {\n return value.then((data) => [].concat(data));\n }\n return [].concat(value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'BiasAdd':\n case 'AddV2':\n case 'Add': {\n return [ops.add(\n (getParamValue('a', node, tensorMap, context) as Tensor),\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'AddN': {\n return [ops.addN((\n getParamValue('tensors', node, tensorMap, context) as Tensor[]))];\n }\n case 'FloorMod':\n case 'Mod':\n return [ops.mod(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'Mul':\n return [ops.mul(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'RealDiv':\n case 'Div': {\n return [ops.div(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'DivNoNan': {\n return [ops.divNoNan(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'FloorDiv': {\n return [ops.floorDiv(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Sub': {\n return [ops.sub(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Minimum': {\n return [ops.minimum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Maximum': {\n return [ops.maximum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Pow': {\n return [ops.pow(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'SquaredDifference': {\n return [ops.squaredDifference(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'arithmetic';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Abs':\n case 'ComplexAbs':\n return [ops.abs(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acos':\n return [ops.acos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acosh':\n return [ops.acosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asin':\n return [ops.asin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asinh':\n return [ops.asinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan':\n return [ops.atan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan2':\n return [ops.atan2(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor)];\n case 'Atanh':\n return [ops.atanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Ceil':\n return [ops.ceil(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Complex':\n return [ops.complex(\n getParamValue('real', node, tensorMap, context) as Tensor,\n getParamValue('imag', node, tensorMap, context) as Tensor)];\n case 'Cos':\n return [ops.cos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Cosh':\n return [ops.cosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Elu':\n return [ops.elu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Erf':\n return [ops.erf(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Exp':\n return [ops.exp(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Expm1': {\n return [ops.expm1(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Floor':\n return [ops.floor(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log':\n return [ops.log(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log1p': {\n return [ops.log1p(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Imag':\n return [ops.imag(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n\n case 'Neg':\n return [ops.neg(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Reciprocal': {\n return [ops.reciprocal(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Real':\n return [ops.real(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Relu':\n return [ops.relu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Round': {\n return [ops.round(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Selu':\n return [ops.selu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sigmoid':\n return [ops.sigmoid(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sin':\n return [ops.sin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sign': {\n return [ops.sign(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sinh': {\n return [ops.sinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Softplus': {\n return [ops.softplus(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sqrt': {\n return [ops.sqrt(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Square': {\n return [ops.square(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tanh': {\n return [ops.tanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tan':\n return [ops.tan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'ClipByValue':\n return [ops.clipByValue(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('clipValueMin', node, tensorMap, context) as number,\n getParamValue('clipValueMax', node, tensorMap, context) as\n number)];\n case 'Relu6':\n return [ops.relu6(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Rsqrt':\n return [ops.rsqrt(getTensor(node.inputNames[0], tensorMap, context))];\n case 'LeakyRelu':\n return [ops.leakyRelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as number)];\n case 'Prelu':\n return [ops.prelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as Tensor)];\n case 'IsNan':\n return [ops.isNaN(getTensor(node.inputNames[0], tensorMap, context))];\n case 'IsInf':\n return [ops.isInf(getTensor(node.inputNames[0], tensorMap, context))];\n case 'IsFinite':\n return [ops.isFinite(\n getTensor(node.inputNames[0], tensorMap, context))];\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'basic_math';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Fill': {\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const value =\n getParamValue('value', node, tensorMap, context) as number;\n return [ops.fill(shape, value, dtype)];\n }\n case 'LinSpace': {\n const start =\n getParamValue('start', node, tensorMap, context) as number;\n const stop =\n getParamValue('stop', node, tensorMap, context) as number;\n const num = getParamValue('num', node, tensorMap, context) as number;\n return [ops.linspace(start, stop, num)];\n }\n case 'Multinomial': {\n const logits =\n getParamValue('logits', node, tensorMap, context) as Tensor1D;\n const numSamples =\n getParamValue('numSamples', node, tensorMap, context) as number;\n const seed =\n getParamValue('seed', node, tensorMap, context) as number;\n return [ops.multinomial(logits, numSamples, seed)];\n }\n case 'OneHot': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n const depth =\n getParamValue('depth', node, tensorMap, context) as number;\n const onValue =\n getParamValue('onValue', node, tensorMap, context) as number;\n const offValue =\n getParamValue('offValue', node, tensorMap, context) as number;\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n return [ops.oneHot(indices, depth, onValue, offValue, dtype)];\n }\n case 'Ones': {\n return [ops.ones(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'OnesLike': {\n return [ops.onesLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RandomStandardNormal': {\n return [ops.randomStandardNormal(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32',\n getParamValue('seed', node, tensorMap, context) as number)];\n }\n case 'RandomUniform': {\n return [ops.randomUniform(\n // tslint:disable-next-line:no-any\n getParamValue('shape', node, tensorMap, context) as any,\n getParamValue('minval', node, tensorMap, context) as number,\n getParamValue('maxval', node, tensorMap, context) as number,\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'RandomUniformInt': {\n return [ops.randomUniformInt(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('minval', node, tensorMap, context) as number,\n getParamValue('maxval', node, tensorMap, context) as number,\n getParamValue('seed', node, tensorMap, context) as number)];\n }\n case 'Range': {\n const start =\n getParamValue('start', node, tensorMap, context) as number;\n const stop =\n getParamValue('stop', node, tensorMap, context) as number;\n const step =\n getParamValue('step', node, tensorMap, context) as number;\n return [ops.range(\n start, stop, step,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32')];\n }\n case 'TruncatedNormal': {\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n const mean =\n getParamValue('mean', node, tensorMap, context) as number;\n const stdDev =\n getParamValue('stdDev', node, tensorMap, context) as number;\n const seed =\n getParamValue('seed', node, tensorMap, context) as number;\n return [ops.truncatedNormal(\n shape, mean, stdDev,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32',\n seed)];\n }\n case 'Zeros': {\n return [ops.zeros(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'ZerosLike': {\n return [ops.zerosLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'creation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps):\n Tensor[] => {\n switch (node.op) {\n case 'LowerBound': {\n const sortedSequence =\n getParamValue('sortedSequence', node, tensorMap, context) as\n Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n return [ops.lowerBound(sortedSequence, values)];\n }\n case 'TopKV2': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const k = getParamValue('k', node, tensorMap, context) as number;\n const sorted =\n getParamValue('sorted', node, tensorMap, context) as boolean;\n const result = ops.topk(x, k, sorted);\n return [result.values, result.indices];\n }\n case 'UpperBound': {\n const sortedSequence =\n getParamValue('sortedSequence', node, tensorMap, context) as\n Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n return [ops.upperBound(sortedSequence, values)];\n }\n case 'Unique': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const result = ops.unique(x);\n return [result.values, result.indices];\n }\n case 'UniqueV2': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const result = ops.unique(x, axis);\n return [result.values, result.indices];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'evaluation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'ResizeBilinear': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const size =\n getParamValue('size', node, tensorMap, context) as number[];\n const alignCorners =\n getParamValue('alignCorners', node, tensorMap, context) as\n boolean;\n const halfPixelCenters =\n getParamValue('halfPixelCenters', node, tensorMap, context) as\n boolean;\n return [ops.image.resizeBilinear(\n images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n halfPixelCenters)];\n }\n case 'ResizeNearestNeighbor': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const size =\n getParamValue('size', node, tensorMap, context) as number[];\n const alignCorners =\n getParamValue('alignCorners', node, tensorMap, context) as\n boolean;\n const halfPixelCenters =\n getParamValue('halfPixelCenters', node, tensorMap, context) as\n boolean;\n return [ops.image.resizeNearestNeighbor(\n images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n halfPixelCenters)];\n }\n case 'CropAndResize': {\n const image =\n getParamValue('image', node, tensorMap, context) as Tensor;\n const boxes =\n getParamValue('boxes', node, tensorMap, context) as Tensor;\n const boxInd =\n getParamValue('boxInd', node, tensorMap, context) as Tensor;\n const cropSize =\n getParamValue('cropSize', node, tensorMap, context) as number[];\n const method =\n getParamValue('method', node, tensorMap, context) as string;\n const extrapolationValue =\n getParamValue('extrapolationValue', node, tensorMap, context) as\n number;\n return [ops.image.cropAndResize(\n image as Tensor4D, boxes as Tensor2D, boxInd as Tensor1D,\n cropSize as [number, number], method as 'bilinear' | 'nearest',\n extrapolationValue)];\n }\n case 'ImageProjectiveTransformV3': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const transforms =\n getParamValue('transforms', node, tensorMap, context) as Tensor;\n const outputShape =\n getParamValue('outputShape', node, tensorMap, context) as\n number[];\n const fillValue =\n getParamValue('fillValue', node, tensorMap, context) as number;\n const interpolation =\n getParamValue('interpolation', node, tensorMap, context) as\n string;\n const fillMode =\n getParamValue('fillMode', node, tensorMap, context) as string;\n return [ops.image.transform(\n images as Tensor4D,\n transforms as Tensor2D,\n interpolation.toLowerCase() as 'bilinear' | 'nearest',\n fillMode.toLowerCase() as 'constant' | 'reflect' | 'wrap' | 'nearest',\n fillValue,\n outputShape as [number, number])];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'image';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Const': {\n return tensorMap[node.name];\n }\n case 'PlaceholderWithDefault':\n const def =\n getParamValue('default', node, tensorMap, context) as Tensor;\n return [getTensor(node.name, tensorMap, context) || def];\n case 'Placeholder':\n return [getTensor(node.name, tensorMap, context)];\n case 'Identity':\n case 'StopGradient':\n case 'FakeQuantWithMinMaxVars': { // This op is currently ignored.\n const data = getParamValue('x', node, tensorMap, context) as Tensor;\n return [cloneTensor(data)];\n }\n case 'IdentityN':\n return (getParamValue('x', node, tensorMap, context) as Tensor[])\n .map((t: Tensor) => cloneTensor(t));\n case 'Snapshot':\n const snapshot =\n (getParamValue('x', node, tensorMap, context) as Tensor);\n return [cloneTensor(snapshot)];\n case 'Shape':\n return [ops.tensor1d(\n (getParamValue('x', node, tensorMap, context) as Tensor).shape,\n 'int32')];\n case 'ShapeN':\n return (getParamValue('x', node, tensorMap, context) as Tensor[])\n .map((t: Tensor) => ops.tensor1d(t.shape));\n case 'Size':\n return [ops.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).size,\n 'int32')];\n case 'Rank':\n return [ops.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).rank,\n 'int32')];\n case 'NoOp':\n return [ops.scalar(1)];\n case 'Print':\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const data =\n getParamValue('data', node, tensorMap, context) as Tensor[];\n const message =\n getParamValue('message', node, tensorMap, context) as string;\n const summarize =\n getParamValue('summarize', node, tensorMap, context) as number;\n console.warn(\n 'The graph has a tf.print() operation,' +\n 'usually used for debugging, which slows down performance.');\n console.log(message);\n for (let i = 0; i < data.length; i++) {\n console.log(Array.prototype.slice.call(data[i].dataSync())\n .slice(0, summarize));\n }\n return [input];\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'graph';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Equal': {\n return [ops.equal(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'NotEqual': {\n return [ops.notEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Greater': {\n return [ops.greater(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'GreaterEqual': {\n return [ops.greaterEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Less': {\n return [ops.less(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LessEqual': {\n return [ops.lessEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalAnd': {\n return [ops.logicalAnd(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalNot': {\n return [ops.logicalNot(\n getParamValue('a', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalOr': {\n return [ops.logicalOr(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Select':\n case 'SelectV2': {\n return [ops.where(\n getParamValue('condition', node, tensorMap, context) as Tensor,\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'BitwiseAnd': {\n return [ops.bitwiseAnd(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'logical';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'BatchMatMul':\n case 'BatchMatMulV2':\n case 'MatMul':\n return [ops.matMul(\n getParamValue('a', node, tensorMap, context) as Tensor2D,\n getParamValue('b', node, tensorMap, context) as Tensor2D,\n getParamValue('transposeA', node, tensorMap, context) as boolean,\n getParamValue('transposeB', node, tensorMap, context) as\n boolean)];\n\n case 'Einsum':\n return [ops.einsum(\n getParamValue('equation', node, tensorMap, context) as string,\n ...getParamValue('tensors', node, tensorMap, context) as\n Tensor[])];\n\n case 'Transpose':\n return [ops.transpose(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('perm', node, tensorMap, context) as number[])];\n\n case '_FusedMatMul':\n const [extraOp, activationFunc] =\n (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n const isBiasAdd = extraOp === 'biasadd';\n const isPrelu = activationFunc === 'prelu';\n\n const numArgs =\n (getParamValue('numArgs', node, tensorMap, context) as number);\n const leakyreluAlpha =\n getParamValue('leakyreluAlpha', node, tensorMap, context) as\n number;\n\n if (isBiasAdd) {\n if (isPrelu && numArgs !== 2) {\n throw new Error(\n 'Fused MatMul with BiasAdd and Prelu must have two ' +\n 'extra arguments: bias and alpha.');\n }\n if (!isPrelu && numArgs !== 1) {\n throw new Error(\n 'Fused MatMul with BiasAdd must have one extra argument: bias.');\n }\n }\n const [biasArg, preluArg] =\n getParamValue('args', node, tensorMap, context) as Tensor[];\n return [ops.fused.matMul({\n a: getParamValue('a', node, tensorMap, context) as Tensor2D,\n b: getParamValue('b', node, tensorMap, context) as Tensor2D,\n transposeA: getParamValue('transposeA', node, tensorMap, context) as\n boolean,\n transposeB: getParamValue('transposeB', node, tensorMap, context) as\n boolean,\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n\n case 'MatrixBandPart':\n return [ops.linalg.bandPart(\n getParamValue('a', node, tensorMap, context) as Tensor2D,\n getParamValue('numLower', node, tensorMap, context) as Scalar,\n getParamValue('numUpper', node, tensorMap, context) as Scalar)];\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'matrices';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'EuclideanNorm':\n return [ops.euclideanNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('axis', node, tensorMap, context) as number[],\n getParamValue('keepDims', node, tensorMap, context) as boolean)];\n case 'FusedBatchNorm':\n case 'FusedBatchNormV2': {\n return [ops.batchNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('mean', node, tensorMap, context) as Tensor,\n getParamValue('variance', node, tensorMap, context) as Tensor,\n getParamValue('offset', node, tensorMap, context) as Tensor,\n getParamValue('scale', node, tensorMap, context) as Tensor,\n getParamValue('epsilon', node, tensorMap, context) as number)];\n }\n case 'FusedBatchNormV3': {\n return [ops.batchNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('mean', node, tensorMap, context) as Tensor,\n getParamValue('variance', node, tensorMap, context) as Tensor,\n getParamValue('offset', node, tensorMap, context) as Tensor,\n getParamValue('scale', node, tensorMap, context) as Tensor,\n getParamValue('epsilon', node, tensorMap, context) as number)];\n }\n case 'LRN': {\n return [ops.localResponseNormalization(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('radius', node, tensorMap, context) as number,\n getParamValue('bias', node, tensorMap, context) as number,\n getParamValue('alpha', node, tensorMap, context) as number,\n getParamValue('beta', node, tensorMap, context) as number)];\n }\n case 'Softmax': {\n return [ops.softmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'LogSoftmax': {\n return [ops.logSoftmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'normalization';\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'RaggedGather': {\n const {\n outputNestedSplits,\n outputDenseValues,\n } =\n ops.raggedGather(\n getParamValue(\n 'paramsNestedSplits', node, tensorMap, context) as\n Tensor[],\n getParamValue(\n 'paramsDenseValues', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor,\n getParamValue('outputRaggedRank', node, tensorMap, context) as\n number);\n return outputNestedSplits.concat(outputDenseValues);\n }\n case 'RaggedRange': {\n const {rtNestedSplits, rtDenseValues} = ops.raggedRange(\n getParamValue('starts', node, tensorMap, context) as Tensor,\n getParamValue('limits', node, tensorMap, context) as Tensor,\n getParamValue('splits', node, tensorMap, context) as Tensor);\n return [rtNestedSplits, rtDenseValues];\n }\n case 'RaggedTensorToTensor': {\n return [ops.raggedTensorToTensor(\n getParamValue('shape', node, tensorMap, context) as Tensor,\n getParamValue('values', node, tensorMap, context) as Tensor1D,\n getParamValue('defaultValue', node, tensorMap, context) as Tensor,\n getParamValue('rowPartitionTensors', node, tensorMap, context) as\n Tensor[],\n getParamValue('rowPartitionTypes', node, tensorMap, context) as\n string[])];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'ragged';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Max': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.max(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Mean': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.mean(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Min': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.min(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Sum': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.sum(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'All': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.all(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Any': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.any(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'ArgMax': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [ops.argMax(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'ArgMin': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [ops.argMin(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'Prod': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [ops.prod(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Cumprod': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const exclusive =\n getParamValue('exclusive', node, tensorMap, context) as boolean;\n const reverse =\n getParamValue('reverse', node, tensorMap, context) as boolean;\n return [ops.cumprod(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n exclusive, reverse)];\n }\n case 'Cumsum': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const exclusive =\n getParamValue('exclusive', node, tensorMap, context) as boolean;\n const reverse =\n getParamValue('reverse', node, tensorMap, context) as boolean;\n return [ops.cumsum(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n exclusive, reverse)];\n }\n case 'Bincount':\n const x = getParamValue('x', node, tensorMap, context) as Tensor1D;\n const weights =\n getParamValue('weights', node, tensorMap, context) as Tensor1D;\n const size =\n getParamValue('size', node, tensorMap, context) as number;\n\n return [ops.bincount(x, weights, size)];\n case 'DenseBincount': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor1D |\n Tensor2D;\n const weights =\n getParamValue('weights', node, tensorMap, context) as Tensor1D |\n Tensor2D;\n const size =\n getParamValue('size', node, tensorMap, context) as number;\n\n const binaryOutput =\n getParamValue('binaryOutput', node, tensorMap, context) as\n boolean;\n\n return [ops.denseBincount(x, weights, size, binaryOutput)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'reduction';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, tidy, util} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'ConcatV2':\n case 'Concat': {\n const n = getParamValue('n', node, tensorMap, context) as number;\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n let inputs =\n getParamValue('tensors', node, tensorMap, context) as Tensor[];\n inputs = inputs.slice(0, n);\n return [ops.concat(inputs, axis)];\n }\n case 'Gather': {\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n return [ops.gather(input, ops.cast(indices, 'int32'), 0)];\n }\n case 'GatherV2': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const batchDims =\n getParamValue('batchDims', node, tensorMap, context) as number;\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n return [ops.gather(\n input, ops.cast(indices, 'int32'), axis, batchDims)];\n }\n case 'Reverse': {\n const dims =\n getParamValue('dims', node, tensorMap, context) as boolean[];\n const axis = [];\n for (let i = 0; i < dims.length; i++) {\n if (dims[i]) {\n axis.push(i);\n }\n }\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n return [ops.reverse(input, axis)];\n }\n case 'ReverseV2': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n return [ops.reverse(input, axis)];\n }\n case 'Slice': {\n // tslint:disable-next-line:no-any\n const begin = getParamValue('begin', node, tensorMap, context) as any;\n // tslint:disable-next-line:no-any\n const size = getParamValue('size', node, tensorMap, context) as any;\n return [ops.slice(\n getParamValue('x', node, tensorMap, context) as Tensor, begin,\n size)];\n }\n case 'StridedSlice': {\n const begin =\n getParamValue('begin', node, tensorMap, context) as number[];\n const end =\n getParamValue('end', node, tensorMap, context) as number[];\n const strides =\n getParamValue('strides', node, tensorMap, context) as number[];\n const beginMask =\n getParamValue('beginMask', node, tensorMap, context) as number;\n const endMask =\n getParamValue('endMask', node, tensorMap, context) as number;\n const ellipsisMask =\n getParamValue('ellipsisMask', node, tensorMap, context) as number;\n const newAxisMask =\n getParamValue('newAxisMask', node, tensorMap, context) as number;\n const shrinkAxisMask =\n getParamValue('shrinkAxisMask', node, tensorMap, context) as\n number;\n const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n return [ops.stridedSlice(\n tensor, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask)];\n }\n case 'Pack': {\n return tidy(() => {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const tensors =\n getParamValue('tensors', node, tensorMap, context) as Tensor[];\n // Reshape the tensors to the first tensor's shape if they don't\n // match.\n const shape = tensors[0].shape;\n const squeezedShape = ops.squeeze(tensors[0]).shape;\n const mapped = tensors.map(tensor => {\n const sameShape = util.arraysEqual(tensor.shape, shape);\n if (!sameShape &&\n !util.arraysEqual(ops.squeeze(tensor).shape, squeezedShape)) {\n throw new Error('the input tensors shape does not match');\n }\n return sameShape ? tensor : ops.reshape(tensor, shape);\n });\n return [ops.stack(mapped, axis)];\n });\n }\n case 'Unpack': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n return ops.unstack(tensor, axis);\n }\n case 'Tile': {\n const reps =\n getParamValue('reps', node, tensorMap, context) as number[];\n return [ops.tile(\n getParamValue('x', node, tensorMap, context) as Tensor, reps)];\n }\n case 'Split':\n case 'SplitV': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const numOrSizeSplits =\n getParamValue('numOrSizeSplits', node, tensorMap, context) as\n number |\n number[];\n const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n return ops.split(tensor, numOrSizeSplits, axis);\n }\n case 'ScatterNd': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n return [ops.scatterND(indices, values, shape)];\n }\n case 'GatherNd': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n return [ops.gatherND(x, indices)];\n }\n case 'SparseToDense': {\n const indices =\n getParamValue('sparseIndices', node, tensorMap, context) as\n Tensor;\n const shape =\n getParamValue('outputShape', node, tensorMap, context) as\n number[];\n const sparseValues =\n getParamValue('sparseValues', node, tensorMap, context) as Tensor;\n const defaultValue =\n getParamValue('defaultValue', node, tensorMap, context) as Scalar;\n return [ops.sparseToDense(\n indices, sparseValues, shape,\n sparseValues.dtype === defaultValue.dtype ?\n defaultValue :\n ops.cast(defaultValue, sparseValues.dtype))];\n }\n case 'TensorScatterUpdate': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n return [ops.tensorScatterUpdate(tensor, indices, values)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'slice_join';\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'SparseFillEmptyRows': {\n const {\n outputIndices,\n outputValues,\n emptyRowIndicator,\n reverseIndexMap\n } =\n ops.sparse.sparseFillEmptyRows(\n getParamValue('indices', node, tensorMap, context) as\n Tensor2D,\n getParamValue('values', node, tensorMap, context) as Tensor1D,\n getParamValue('denseShape', node, tensorMap, context) as\n Tensor1D,\n getParamValue('defaultValue', node, tensorMap, context) as\n Scalar);\n return [\n outputIndices, outputValues, emptyRowIndicator, reverseIndexMap\n ];\n }\n case 'SparseReshape': {\n const {outputIndices, outputShape} = ops.sparse.sparseReshape(\n getParamValue('inputIndices', node, tensorMap, context) as\n Tensor2D,\n getParamValue('inputShape', node, tensorMap, context) as Tensor1D,\n getParamValue('newShape', node, tensorMap, context) as Tensor1D);\n return [outputIndices, outputShape];\n }\n case 'SparseSegmentMean': {\n const outputData = ops.sparse.sparseSegmentMean(\n getParamValue('data', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor1D,\n getParamValue('segmentIds', node, tensorMap, context) as\n Tensor1D);\n return [outputData];\n }\n case 'SparseSegmentSum': {\n const outputData = ops.sparse.sparseSegmentSum(\n getParamValue('data', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor1D,\n getParamValue('segmentIds', node, tensorMap, context) as\n Tensor1D);\n return [outputData];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'sparse';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'FFT': {\n return [ops.fft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IFFT': {\n return [ops.ifft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RFFT': {\n return [ops.rfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IRFFT': {\n return [ops.irfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'spectral';\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'StaticRegexReplace': {\n return [ops.string.staticRegexReplace(\n getParamValue('input', node, tensorMap, context) as Tensor,\n getParamValue('pattern', node, tensorMap, context) as string,\n getParamValue('rewrite', node, tensorMap, context) as string,\n getParamValue('replaceGlobal', node, tensorMap, context) as boolean,\n )];\n }\n case 'StringNGrams': {\n const {nGrams, nGramsSplits} = ops.string.stringNGrams(\n getParamValue('data', node, tensorMap, context) as Tensor1D,\n getParamValue('dataSplits', node, tensorMap, context) as Tensor,\n getParamValue('separator', node, tensorMap, context) as string,\n getParamValue('nGramWidths', node, tensorMap, context) as\n number[],\n getParamValue('leftPad', node, tensorMap, context) as string,\n getParamValue('rightPad', node, tensorMap, context) as string,\n getParamValue('padWidth', node, tensorMap, context) as number,\n getParamValue(\n 'preserveShortSequences', node, tensorMap, context) as\n boolean);\n return [nGrams, nGramsSplits];\n }\n case 'StringSplit': {\n const {indices, values, shape} = ops.string.stringSplit(\n getParamValue('input', node, tensorMap, context) as Tensor1D,\n getParamValue('delimiter', node, tensorMap, context) as Scalar,\n getParamValue('skipEmpty', node, tensorMap, context) as boolean);\n return [indices, values, shape];\n }\n case 'StringToHashBucketFast': {\n const output = ops.string.stringToHashBucketFast(\n getParamValue('input', node, tensorMap, context) as Tensor,\n getParamValue('numBuckets', node, tensorMap, context) as number);\n return [output];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'string';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n ops = tfOps): Tensor[] => {\n switch (node.op) {\n case 'Cast': {\n return [ops.cast(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('dtype', node, tensorMap, context) as 'int32' |\n 'float32' | 'bool')];\n }\n case 'ExpandDims': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [ops.expandDims(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'Squeeze': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n return [ops.squeeze(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n\n case 'Reshape': {\n return [ops.reshape(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'EnsureShape': {\n return [ops.ensureShape(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'MirrorPad': {\n return [ops.mirrorPad(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('padding', node, tensorMap, context) as\n Array<[number, number]>,\n getParamValue('mode', node, tensorMap, context) as 'reflect' |\n 'symmetric')];\n }\n case 'PadV2':\n case 'Pad': {\n return [ops.pad(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('padding', node, tensorMap, context) as\n Array<[number, number]>,\n getParamValue('constantValue', node, tensorMap, context) as\n number)];\n }\n case 'SpaceToBatchND': {\n const blockShape =\n getParamValue('blockShape', node, tensorMap, context) as number[];\n const paddings =\n getParamValue('paddings', node, tensorMap, context) as number[][];\n return [ops.spaceToBatchND(\n getParamValue('x', node, tensorMap, context) as Tensor,\n blockShape, paddings)];\n }\n case 'BatchToSpaceND': {\n const blockShape =\n getParamValue('blockShape', node, tensorMap, context) as number[];\n const crops =\n getParamValue('crops', node, tensorMap, context) as number[][];\n return [ops.batchToSpaceND(\n getParamValue('x', node, tensorMap, context) as Tensor,\n blockShape, crops)];\n }\n case 'DepthToSpace': {\n const blockSize =\n getParamValue('blockSize', node, tensorMap, context) as number;\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as\n string).toUpperCase() as 'NHWC' |\n 'NCHW';\n return [ops.depthToSpace(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n blockSize, dataFormat)];\n }\n case 'BroadcastTo': {\n return [ops.broadcastTo(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'BroadcastArgs': {\n return [ops.broadcastArgs(\n getParamValue('s0', node, tensorMap, context) as Tensor,\n getParamValue('s1', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'transformation';\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 => {\n switch (node.op) {\n case 'HashTable':\n case 'HashTableV2': {\n const existingTableHandle =\n resourceManager.getHashTableHandleByName(node.name);\n // Table is shared with initializer.\n if (existingTableHandle != null) {\n return [existingTableHandle];\n } else {\n const keyDType =\n getParamValue('keyDType', node, tensorMap, context) as DataType;\n const valueDType =\n getParamValue('valueDType', node, tensorMap, context) as DataType;\n\n const hashTable = new HashTable(keyDType, valueDType);\n resourceManager.addHashTable(node.name, hashTable);\n return [hashTable.handle];\n }\n }\n case 'InitializeTable':\n case 'InitializeTableV2':\n case 'LookupTableImport':\n case 'LookupTableImportV2': {\n const handle = getParamValue(\n 'tableHandle', node, tensorMap, context,\n resourceManager) as Tensor;\n const keys = getParamValue('keys', node, tensorMap, context) as Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n\n const hashTable = resourceManager.getHashTableById(handle.id);\n\n return [await hashTable.import(keys, values)];\n }\n case 'LookupTableFind':\n case 'LookupTableFindV2': {\n const handle = getParamValue(\n 'tableHandle', node, tensorMap, context,\n resourceManager) as Tensor;\n const keys = getParamValue('keys', node, tensorMap, context) as Tensor;\n const defaultValue =\n getParamValue('defaultValue', node, tensorMap, context) as Tensor;\n\n const hashTable = resourceManager.getHashTableById(handle.id);\n return [await hashTable.find(keys, defaultValue)];\n }\n case 'LookupTableSize':\n case 'LookupTableSizeV2': {\n const handle = getParamValue(\n 'tableHandle', node, tensorMap, context,\n resourceManager) as Tensor;\n\n const hashTable = resourceManager.getHashTableById(handle.id);\n return [hashTable.tensorSize()];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'hash_table';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap, TensorArrayMap, TensorListMap} from '../data/types';\n\nimport {TensorArray} from './tensor_array';\nimport {TensorList} from './tensor_list';\nimport {FunctionExecutor} from './types';\n\nexport interface ExecutionContextInfo {\n id: number; // the unique id of the context info\n frameName: string; // The frame name of the loop, this comes from\n // the TensorFlow NodeDef.\n iterationId: number; // The iteration id of the loop\n}\n\n/**\n * ExecutionContext captures the runtime environment of the node. It keeps\n * track of the current frame and iteration for the control flow ops.\n *\n * For example, typical Dynamic RNN model may contain loops, for which\n * TensorFlow will generate graphs with Enter/Exit nodes to control the\n * current execution frame, and NextIteration Nodes for iteration id increment.\n * For model with branch logic, TensorFLow will generate Switch/Merge ops.\n */\nexport class ExecutionContext {\n private rootContext = {id: 0, frameName: '', iterationId: 0};\n private contexts: ExecutionContextInfo[] = [this.rootContext];\n private lastId = 0;\n private _currentContextIds: string[];\n\n constructor(\n readonly weightMap: NamedTensorsMap = {},\n readonly tensorArrayMap: TensorArrayMap = {},\n readonly tensorListMap: TensorListMap = {},\n readonly functionMap: {[key: string]: FunctionExecutor} = {},\n readonly parseNodeNameCache?: Map) {\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) {\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;\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();\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();\n const inputNodeNames =\n new Set(Object.keys(inputs).map((name) => parseNodeName(name)[0]));\n\n initNodes = initNodes || [];\n const initNodeNames =\n new Set(initNodes.map((node) => parseNodeName(node.name)[0]));\n\n const frontier = [...outputs];\n while (frontier.length > 0) {\n const node = frontier.pop();\n if (isControlFlow(node) || isDynamicShape(node) || isHashTable(node)) {\n if (dynamicNode == null) {\n dynamicNode = node;\n syncInputs = dynamicNode.children.map(child => child.name)\n .filter(name => usedNodes.has(name));\n }\n }\n usedNodes.add(node.name);\n\n // Weights are dead end since we already have their values.\n if (weightMap[node.name] != null) {\n continue;\n }\n // This node is a dead end since it's one of the user-provided inputs.\n if (inputNodeNames.has(node.name)) {\n continue;\n }\n // This node is a dead end since it doesn't have any inputs.\n if (initNodeNames.has(node.name)) {\n continue;\n }\n if (node.inputs.length === 0) {\n missingInputs.push(node.name);\n continue;\n }\n node.inputs.forEach(input => {\n // Don't add to the frontier if it is already there.\n if (seen.has(input.name)) {\n return;\n }\n seen.add(input.name);\n frontier.push(input);\n });\n }\n return {inputs, outputs, usedNodes, missingInputs, dynamicNode, syncInputs};\n}\n\n/**\n * Given the execution info, return a list of nodes in topological order that\n * need to be executed to compute the output.\n */\nexport function getNodesInTopologicalOrder(\n graph: Graph, executionInfo: ExecutionInfo): Node[] {\n const {usedNodes, inputs} = executionInfo;\n const inputNodes = Object.keys(inputs)\n .map(name => parseNodeName(name)[0])\n .map(name => graph.nodes[name]);\n const initNodes = graph.initNodes || [];\n\n const isUsed = (node: Node|string) =>\n usedNodes.has(typeof node === 'string' ? node : node.name);\n\n function unique(nodes: Node[]): Node[] {\n return [...new Map(nodes.map((node) => [node.name, node])).values()];\n }\n const predefinedNodes = unique([\n ...inputNodes,\n ...graph.weights,\n ...initNodes,\n ]).filter(isUsed);\n const allNodes = unique([\n ...predefinedNodes,\n ...Object.values(graph.nodes),\n ]).filter(isUsed);\n const nameToNode =\n new Map(allNodes.map((node) => [node.name, node]));\n\n const inCounts: Record = {};\n for (const node of allNodes) {\n inCounts[node.name] = inCounts[node.name] || 0;\n for (const child of node.children) {\n // When the child is unused, set in counts to infinity so that it will\n // never be decreased to 0 and added to the execution list.\n if (!isUsed(child)) {\n inCounts[child.name] = Number.POSITIVE_INFINITY;\n }\n inCounts[child.name] = (inCounts[child.name] || 0) + 1;\n }\n }\n\n // Build execution order for all used nodes regardless whether they are\n // predefined or not.\n const frontier = Object.entries(inCounts)\n .filter(([, inCount]) => inCount === 0)\n .map(([name]) => name);\n const orderedNodeNames = [...frontier];\n while (frontier.length > 0) {\n const nodeName = frontier.pop();\n const node = nameToNode.get(nodeName)!;\n for (const child of node.children.filter(isUsed)) {\n if (--inCounts[child.name] === 0) {\n orderedNodeNames.push(child.name);\n frontier.push(child.name);\n }\n }\n }\n\n const orderedNodes = orderedNodeNames.map((name) => nameToNode.get(name));\n const filteredOrderedNodes =\n filterPredefinedReachableNodes(orderedNodes, predefinedNodes);\n\n // TODO: Turn validation on/off with tf env flag.\n validateNodesExecutionOrder(filteredOrderedNodes, predefinedNodes);\n\n return filteredOrderedNodes;\n}\n\n/**\n * This is a helper function of `getNodesInTopologicalOrder`.\n * Returns ordered nodes reachable by at least one predefined node.\n * This can help us filter out redundant nodes from the returned node list.\n * For example:\n * If we have four nodes with dependencies like this:\n * a --> b --> c --> d\n * when node `c` is predefined (e.g. given as an input tensor), we can\n * skip node `a` and `b` since their outputs will never be used.\n *\n * @param orderedNodes Graph nodes in execution order.\n * @param predefinedNodes Graph inputs, weights, and init nodes. Nodes in this\n * list must have distinct names.\n */\nfunction filterPredefinedReachableNodes(\n orderedNodes: Node[], predefinedNodes: Node[]) {\n const nameToNode =\n new Map(orderedNodes.map((node) => [node.name, node]));\n\n // TODO: Filter out more nodes when >=2 nodes are predefined in a path.\n const stack = predefinedNodes.map((node) => node.name);\n const predefinedReachableNodeNames = new Set(stack);\n // Perform a DFS starting from the set of all predefined nodes\n // to find the set of all nodes reachable from the predefined nodes.\n while (stack.length > 0) {\n const nodeName = stack.pop();\n const node = nameToNode.get(nodeName)!;\n for (const child of node.children) {\n if (!nameToNode.has(child.name) ||\n predefinedReachableNodeNames.has(child.name)) {\n continue;\n }\n predefinedReachableNodeNames.add(child.name);\n stack.push(child.name);\n }\n }\n\n // Filter out unreachable nodes and build the ordered node list.\n const filteredOrderedNodes = orderedNodes.filter(\n (node) => predefinedReachableNodeNames.has(node.name));\n\n return filteredOrderedNodes;\n}\n\nclass NodesExecutionOrderError extends Error {\n constructor(message: string) {\n super(`NodesExecutionOrderError: ${message}`);\n }\n}\n\n/**\n * This is a helper function of `getNodesInTopologicalOrder`.\n * Validates property: given nodes `a` and `b`, Order(a) > Order(b) if `a`\n * is a child of `b`. This function throws an error if validation fails.\n *\n * @param orderedNodes Graph nodes in execution order.\n * @param predefinedNodes Graph inputs, weights, and init nodes. Nodes in this\n * list must have distinct names.\n */\nfunction validateNodesExecutionOrder(\n orderedNodes: Node[], predefinedNodes: Node[]) {\n const nodeNameToOrder = new Map(\n orderedNodes.map((node, order) => [node.name, order]));\n const predefinedNodeNames = new Set(predefinedNodes.map((node) => node.name));\n const isPredefined = (node: Node|string) =>\n predefinedNodeNames.has(typeof node === 'string' ? node : node.name);\n const willBeExecutedNodeNames =\n new Set(orderedNodes.map((node) => node.name));\n const willBeExecuted = (node: Node|string) =>\n willBeExecutedNodeNames.has(typeof node === 'string' ? node : node.name);\n\n for (const node of orderedNodes) {\n for (const child of node.children.filter(willBeExecuted)) {\n if (!nodeNameToOrder.has(child.name)) {\n throw new NodesExecutionOrderError(\n `Child ${child.name} of node ${node.name} is unreachable.`);\n }\n if (nodeNameToOrder.get(node.name) > nodeNameToOrder.get(child.name)) {\n throw new NodesExecutionOrderError(`Node ${\n node.name} is scheduled to run after its child ${child.name}.`);\n }\n }\n if (!isPredefined(node)) {\n for (const input of node.inputs) {\n if (!nodeNameToOrder.has(input.name)) {\n throw new NodesExecutionOrderError(\n `Input ${input.name} of node ${node.name} is unreachable.`);\n }\n if (nodeNameToOrder.get(input.name) > nodeNameToOrder.get(node.name)) {\n throw new NodesExecutionOrderError(`Node ${\n node.name} is scheduled to run before its input ${input.name}.`);\n }\n }\n }\n }\n}\n\n/**\n * Given the execution info, return a map from node name to the disposable\n * node name list after its execution.\n *\n * @returns A map from node name to disposable nodes after its\n * execution. That is, for a node `x`, `nodeLiveUntilMap[x]` indicates\n * all nodes which their intermediate tensors should be disposed after `x`\n * being executed.\n */\nexport function getNodeLiveUntilMap(orderedNodes: Node[]): Map {\n const nodeNameToOrder = new Map(\n orderedNodes.map((node, order) => [node.name, order]));\n\n const INF_LIFE = Number.MAX_SAFE_INTEGER;\n // Make control flow nodes (and consequently their direct parents)\n // live forever since they're tricky to track correctly.\n const selfLifespans = orderedNodes.map(\n (node, nodeOrder) => isControlFlow(node) ? INF_LIFE : nodeOrder);\n const getSelfLifeSpan = (node: Node) => {\n const selfLife = selfLifespans[nodeNameToOrder.get(node.name)!];\n if (selfLife == null) {\n // If nodeToOrder does not contain the node, it is unused or\n // unreachable in graph.\n return -1;\n }\n return selfLife;\n };\n\n // `liveUntil[i]` points to the last node in the `orderedNodes` array that\n // may depend on tensors from node `i`. It indicates that all the\n // intermediate tensors from `orderedNodes[i]` should be disposed after\n // `orderedNodes[liveUntil[i]]` is executed.\n // A node lives long enough to pass on its tensors to its children.\n // It lives until at least `max(node's position, children's positions)`.\n const liveUntilOrders = orderedNodes.map((node, nodeOrder) => {\n return node.children.map(getSelfLifeSpan)\n .reduce((a, b) => Math.max(a, b), selfLifespans[nodeOrder]);\n });\n\n // liveUntilMap:\n // - Key: Name of a node `x`\n // - Values: All nodes whose intermediate tensors should be disposed\n // after `x` is executed.\n const liveUntilMap = new Map();\n for (let nodeOrder = 0; nodeOrder < orderedNodes.length; ++nodeOrder) {\n const liveUntilOrder = liveUntilOrders[nodeOrder];\n if (liveUntilOrder === INF_LIFE) {\n continue;\n }\n const node = orderedNodes[nodeOrder];\n const liveUntilNode = orderedNodes[liveUntilOrder];\n if (!liveUntilMap.has(liveUntilNode.name)) {\n liveUntilMap.set(liveUntilNode.name, []);\n }\n liveUntilMap.get(liveUntilNode.name)!.push(node);\n }\n return liveUntilMap;\n}\n\nconst CONTROL_FLOW_OPS = new Set([\n 'Switch', 'Merge', 'Enter', 'Exit', 'NextIteration', 'StatelessIf',\n 'StatelessWhile', 'if', 'While'\n]);\nconst DYNAMIC_SHAPE_OPS = new Set([\n 'NonMaxSuppressionV2', 'NonMaxSuppressionV3', 'NonMaxSuppressionV5', 'Where'\n]);\nconst HASH_TABLE_OPS = new Set([\n 'HashTable', 'HashTableV2', 'LookupTableImport', 'LookupTableImportV2',\n 'LookupTableFind', 'LookupTableFindV2', 'LookupTableSize', 'LookupTableSizeV2'\n]);\n\nexport function isControlFlow(node: Node) {\n return CONTROL_FLOW_OPS.has(node.op);\n}\n\nexport function isDynamicShape(node: Node) {\n return DYNAMIC_SHAPE_OPS.has(node.op);\n}\n\nexport function isHashTable(node: Node) {\n return HASH_TABLE_OPS.has(node.op);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, env, keep, NamedTensorMap, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {ISignatureDef} from '../data/compiled_api';\nimport {NamedTensorsMap, TensorArrayMap, TensorInfo, TensorListMap} from '../data/types';\nimport {getNodeNameAndIndex, getParamValue, getTensor, getTensorsForCurrentContext, parseNodeName} from '../operations/executors/utils';\nimport {executeOp} from '../operations/operation_executor';\nimport {Graph, Node} from '../operations/types';\n\nimport {ExecutionContext, ExecutionContextInfo} from './execution_context';\nimport {getExecutionSubgraph, getNodeLiveUntilMap, getNodesInTopologicalOrder, isControlFlow} from './model_analysis';\nimport {ResourceManager} from './resource_manager';\nimport {FunctionExecutor} from './types';\n\ninterface NodeWithContexts {\n contexts: ExecutionContextInfo[];\n node: Node;\n}\n\nexport class GraphExecutor implements FunctionExecutor {\n private compiledMap = new Map>();\n private parseNodeNameCache = 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 SEPARATOR = ',';\n private _functions: {[key: string]: Graph} = {};\n private _functionExecutorMap: {[key: string]: FunctionExecutor} = {};\n private _resourceManager: ResourceManager;\n private clonedTensorsMap: NamedTensorsMap;\n private keepIntermediateTensors = false;\n\n get weightIds(): number[] {\n return this.parent ? this.parent.weightIds : this._weightIds;\n }\n\n get functionExecutorMap(): {[key: string]: FunctionExecutor} {\n return this.parent ? this.parent.functionExecutorMap :\n this._functionExecutorMap;\n }\n\n get weightMap(): NamedTensorsMap {\n return this.parent ? this.parent.weightMap : this._weightMap;\n }\n\n set weightMap(weightMap: NamedTensorsMap) {\n const weightIds = Object.keys(weightMap).map(\n key => weightMap[key].map(tensor => tensor.id));\n this._weightIds = [].concat(...weightIds);\n this._weightMap = weightMap;\n }\n\n /**\n * Set `ResourceManager` shared by executors of a model.\n * @param resourceManager: `ResourceManager` of the `GraphModel`.\n */\n set resourceManager(resourceManager: ResourceManager) {\n this._resourceManager = resourceManager;\n }\n\n get inputs(): TensorInfo[] {\n return this._inputs.map(node => {\n return {\n name: node.name,\n shape: node.attrParams['shape'] ?\n node.attrParams['shape'].value as number[] :\n undefined,\n dtype: node.attrParams['dtype'] ?\n node.attrParams['dtype'].value as DataType :\n undefined\n };\n });\n }\n\n get outputs(): TensorInfo[] {\n return this._outputs.map(node => {\n return {\n name: node.name,\n shape: node.attrParams['shape'] ?\n node.attrParams['shape'].value as number[] :\n undefined,\n dtype: node.attrParams['dtype'] ?\n node.attrParams['dtype'].value as DataType :\n undefined\n };\n });\n }\n\n get inputNodes(): string[] {\n return this._inputs.map(node => node.signatureKey || node.name);\n }\n\n get outputNodes(): string[] {\n return this._outputs.map((node) => {\n const name = node.signatureKey || node.name;\n return node.defaultOutput ? (`${name}:${node.defaultOutput}`) : name;\n });\n }\n\n get functions(): {[key: string]: ISignatureDef} {\n return Object.keys(this._functions).reduce((map, key) => {\n map[key] = this._functions[key].signature;\n return map;\n }, {} as {[key: string]: ISignatureDef});\n }\n\n /**\n *\n * @param graph Graph the model or function graph to be executed.\n * @param parent When building function exector you need to set the parent\n * executor. Since the weights and function executor maps are set at parant\n * level, that function executor can access the function maps and weight maps\n * through the parent.\n */\n constructor(private graph: Graph, private parent?: GraphExecutor) {\n this._outputs = graph.outputs;\n this._inputs = graph.inputs;\n this._initNodes = graph.initNodes;\n this._signature = graph.signature;\n this._functions = graph.functions;\n // create sub-graph executors\n if (graph.functions != null) {\n Object.keys(graph.functions).forEach(name => {\n this._functionExecutorMap[name] =\n new GraphExecutor(graph.functions[name], this);\n });\n }\n }\n\n private getCompilationKey(inputs: Node[], outputs: Node[]): string {\n const sortedInputs = inputs.map(node => node.name).sort();\n const sortedOutputs = outputs.map(node => node.name).sort();\n return sortedInputs.join(this.SEPARATOR) + '--' +\n sortedOutputs.join(this.SEPARATOR);\n }\n\n /**\n * Compiles the inference graph and returns the minimal set of nodes that are\n * required for execution, in the correct execution order.\n * @returns {Object} compilation The compile result.\n * @returns {Node[]} compilation.orderedNodes Nodes in the correct execution\n * order.\n * @returns {Map} compilation.nodeLiveUntilMap A map from node\n * to disposable nodes after its execution. That is, for a node `x`,\n * `nodeLiveUntilMap[x]` indicates all nodes whose intermediate\n * tensors should be disposed after `x` is executed.\n */\n private compile(inputs: NamedTensorMap, outputs: Node[]):\n {orderedNodes: Node[], nodeLiveUntilMap: Map} {\n const executionInfo =\n getExecutionSubgraph(inputs, outputs, this.weightMap, this._initNodes);\n const {missingInputs, dynamicNode, syncInputs} = executionInfo;\n if (dynamicNode != null) {\n throw new Error(\n `This execution contains the node '${dynamicNode.name}', which has ` +\n `the dynamic op '${dynamicNode.op}'. Please use ` +\n `model.executeAsync() instead. Alternatively, to avoid the ` +\n `dynamic ops, specify the inputs [${syncInputs}]`);\n }\n\n if (missingInputs.length > 0) {\n const outNames = outputs.map(n => n.name);\n const inNames = Object.keys(inputs);\n throw new Error(\n `Cannot compute the outputs [${outNames}] from the provided inputs ` +\n `[${inNames}]. Missing the following inputs: [${missingInputs}]`);\n }\n\n const orderedNodes = getNodesInTopologicalOrder(this.graph, executionInfo);\n const nodeLiveUntilMap = getNodeLiveUntilMap(orderedNodes);\n return {orderedNodes, nodeLiveUntilMap};\n }\n\n private cloneAndKeepTensor(tensor: Tensor) {\n if (tensor == null) {\n return null;\n }\n const clone = tensor.clone();\n // Keep the clone because`model.execute()` may be called within\n // a `tidy()`, but the user may inspect these tensors after the\n // tidy.\n keep(clone);\n return clone;\n }\n\n private cloneTensorList(tensors: Tensor[]) {\n if (!tensors) {\n return null;\n }\n const clonedTensor = tensors.map(tensor => {\n return this.cloneAndKeepTensor(tensor);\n });\n return clonedTensor;\n }\n\n private cloneTensorMap(tensorsMap: NamedTensorsMap): NamedTensorsMap {\n return Object.fromEntries(\n Object.entries(tensorsMap).map(([name, tensorsList]) => {\n return [name, this.cloneTensorList(tensorsList)];\n }));\n }\n\n /**\n * Executes the inference for given input tensors.\n * @param inputs Tensor map for the model inputs, keyed by the input node\n * names.\n * @param outputs Optional. output node name from the Tensorflow model, if\n * no outputs are specified, the default outputs of the model would be used.\n * You can inspect intermediate nodes of the model by adding them to the\n * outputs array.\n */\n execute(inputs: NamedTensorMap, outputs?: string[]): Tensor[] {\n // Dispose any tensors from a prior run to avoid leaking them.\n this.disposeIntermediateTensors();\n inputs = this.mapInputs(inputs);\n const names = Object.keys(inputs).sort();\n this.checkInputs(inputs);\n this.checkInputShapeAndType(inputs);\n outputs = this.mapOutputs(outputs);\n this.checkOutputs(outputs);\n const inputNodes =\n names.map(name => this.graph.nodes[parseNodeName(name)[0]]);\n const outputNodeNames = outputs.map(name => parseNodeName(name)[0]);\n const outputNodeNameSet = new Set(outputNodeNames);\n let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n // If no outputs are specified, then use the default outputs of the model.\n if (outputNodes.length === 0) {\n outputNodes = this._outputs;\n }\n\n const compilationKey = this.getCompilationKey(inputNodes, outputNodes);\n\n // Do nothing if the compiled graph cache contains the input.\n let compilation = this.compiledMap.get(compilationKey);\n if (compilation == null) {\n compilation = this.compile(inputs, outputNodes);\n this.compiledMap.set(compilationKey, compilation);\n }\n\n // Keep tensors if KEEP_INTERMEDIATE_TENSORS is on.\n try {\n this.keepIntermediateTensors = env().getBool('KEEP_INTERMEDIATE_TENSORS');\n } catch (e) {\n this.keepIntermediateTensors = false;\n console.warn(e.message);\n }\n const tensorArrayMap: TensorArrayMap = {};\n const tensorListMap: TensorListMap = {};\n\n return tidy(() => {\n const context = new ExecutionContext(\n this.weightMap, tensorArrayMap, tensorListMap,\n this.functionExecutorMap, this.parseNodeNameCache);\n const tensorsMap: NamedTensorsMap = {...this.weightMap};\n if (this.keepIntermediateTensors) {\n this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);\n }\n\n Object.keys(inputs).forEach(name => {\n const [nodeName, index] = parseNodeName(name, context);\n const tensors: Tensor[] = [];\n tensors[index] = inputs[name];\n tensorsMap[nodeName] = tensors;\n if (this.keepIntermediateTensors) {\n this.clonedTensorsMap[nodeName] = this.cloneTensorList(tensors);\n }\n });\n\n const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n const {orderedNodes, nodeLiveUntilMap} = compilation;\n for (const node of orderedNodes) {\n if (tensorsMap[node.name]) {\n continue;\n }\n const tensors =\n executeOp(node, tensorsMap, context, this._resourceManager) as\n Tensor[];\n if (util.isPromise(tensors)) {\n throw new Error(\n `The execution of the op '${node.op}' returned a promise. ` +\n `Please use model.executeAsync() instead.`);\n }\n tensorsMap[node.name] = tensors;\n if (this.keepIntermediateTensors) {\n this.clonedTensorsMap[node.name] = this.cloneTensorList(tensors);\n }\n this.checkTensorForDisposalWithNodeLiveUntilInfo(\n node, tensorsMap, context, tensorsToKeep, outputNodeNameSet,\n nodeLiveUntilMap.get(node.name));\n }\n\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(tensorsToKeep);\n }\n\n return outputs.map(name => getTensor(name, tensorsMap, context));\n });\n }\n\n private getFrozenTensorIds(tensorMap: NamedTensorsMap): Set {\n const ids = [].concat.apply(\n [],\n Object.keys(tensorMap)\n .map(key => tensorMap[key])\n .map(tensors => tensors.map(tensor => tensor.id)));\n return new Set(ids);\n }\n\n private checkTensorForDisposal(\n nodeName: string, node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, tensorsToKeep: Set,\n outputNodeNameSet: Set,\n intermediateTensorConsumerCount: {[key: string]: number}) {\n // Skip output nodes and any control flow nodes, since its dependency is\n // tricky to track correctly.\n if (isControlFlow(node) || outputNodeNameSet.has(nodeName)) {\n return;\n }\n\n for (const tensor of tensorMap[nodeName]) {\n if (tensor == null) {\n continue;\n }\n intermediateTensorConsumerCount[tensor.id] =\n (intermediateTensorConsumerCount[tensor.id] || 0) +\n node.children.length;\n }\n\n for (const input of node.inputs) {\n // Skip any control flow nodes, since its dependency is tricky to track\n // correctly.\n if (isControlFlow(input)) {\n continue;\n }\n\n const tensors =\n getTensorsForCurrentContext(input.name, tensorMap, context);\n if (tensors == null) {\n continue;\n }\n\n for (const tensor of tensors) {\n if (!tensor || tensor.kept || tensorsToKeep.has(tensor.id)) {\n continue;\n }\n\n // Only intermediate nodes' tensors have counts set, not marked as\n // kept, and not in `tensorsToKeep`.\n // Input and weight nodes' tensors should exist in `tensorsToKeep`.\n // Output and control flow nodes' tensors should never have count set.\n const count = intermediateTensorConsumerCount[tensor.id];\n if (count === 1) {\n tensor.dispose();\n delete intermediateTensorConsumerCount[tensor.id];\n } else if (count != null) {\n intermediateTensorConsumerCount[tensor.id]--;\n }\n }\n }\n }\n\n private checkTensorForDisposalWithNodeLiveUntilInfo(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n tensorsToKeep: Set, outputNodeNameSet: Set,\n liveUntilNodes?: Node[]) {\n function isNonDisposableNode(node: Node) {\n // Skip output nodes and any control flow nodes, since its dependency is\n // tricky to track correctly.\n return isControlFlow(node) || outputNodeNameSet.has(node.name);\n }\n\n if (isControlFlow(node) || liveUntilNodes == null) {\n return;\n }\n\n for (const nodeToDispose of liveUntilNodes) {\n if (isNonDisposableNode(nodeToDispose)) {\n continue;\n }\n const tensors = getTensorsForCurrentContext(\n nodeToDispose.name, tensorMap, context);\n for (const tensor of tensors) {\n if (!tensor || tensor.kept || tensorsToKeep.has(tensor.id)) {\n continue;\n }\n tensor.dispose();\n }\n }\n }\n\n /**\n * Executes the inference for given input tensors in Async fashion.\n * @param inputs Tensor map for the model inputs, keyed by the input node\n * names.\n * @param outputs output node name from the Tensorflow model, if no outputs\n * are specified, the default outputs of the model would be used. You can\n * inspect intermediate nodes of the model by adding them to the outputs\n * array.\n */\n async executeAsync(inputs: NamedTensorMap, outputs?: string[]):\n Promise {\n return this._executeAsync(inputs, outputs);\n }\n\n disposeIntermediateTensors() {\n if (!this.clonedTensorsMap) {\n return;\n }\n Object.values(this.clonedTensorsMap).forEach(tensorsList => {\n for (const tensor of tensorsList) {\n if (tensor && !tensor.isDisposed) {\n tensor.dispose();\n }\n }\n });\n\n this.clonedTensorsMap = null;\n }\n\n getIntermediateTensors(): NamedTensorsMap {\n return this.clonedTensorsMap;\n }\n\n /**\n * Executes the inference for given input tensors in Async fashion.\n * @param inputs Tensor map for the model inputs, keyed by the input node\n * names.\n * @param outputs Optional. output node name from the Tensorflow model,\n * if no outputs are specified, the default outputs of the model would be\n * used. You can inspect intermediate nodes of the model by adding them to\n * the outputs array.\n * @param isFunctionExecution Optional. Flag for executing a function.\n * @param tensorArrayMap Optional, global TensorArray map by id. Used for\n * function execution.\n * @param tensorArrayMap 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 {\n // Dispose any tensors from a prior run to avoid leaking them.\n this.disposeIntermediateTensors();\n if (!isFunctionExecution) {\n inputs = this.mapInputs(inputs);\n this.checkInputs(inputs);\n this.checkInputShapeAndType(inputs);\n outputs = this.mapOutputs(outputs);\n this.checkOutputs(outputs);\n }\n\n // Keep tensors if KEEP_INTERMEDIATE_TENSORS is on.\n try {\n this.keepIntermediateTensors = env().getBool('KEEP_INTERMEDIATE_TENSORS');\n } catch (e) {\n this.keepIntermediateTensors = false;\n console.warn(e.message);\n }\n\n const context = new ExecutionContext(\n this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap,\n this.parseNodeNameCache);\n\n if (this.keepIntermediateTensors) {\n this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);\n }\n\n // Graph with control flow op requires runtime evaluation of the execution\n // order, while without control flow the execution order is pre-determined\n // in the compile method.\n const tensorsMap = await this.executeWithControlFlow(\n inputs, context, outputs, isFunctionExecution);\n const results = outputs.map(name => getTensor(name, tensorsMap, context));\n\n // dispose all the intermediate tensors\n const outputIds = results.map(t => t.id);\n const inputIds = Object.keys(inputs).map(name => inputs[name].id);\n const keepIds =\n new Set([...outputIds, ...inputIds, ...this.weightIds]);\n\n Object.values(tensorsMap).forEach(tensorsList => {\n tensorsList.forEach(tensor => {\n if (tensor && !tensor.isDisposed && !keepIds.has(tensor.id)) {\n tensor.dispose();\n }\n });\n });\n\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(keepIds);\n }\n\n return results;\n }\n\n async executeFunctionAsync(\n inputs: Tensor[], tensorArrayMap: TensorArrayMap,\n tensorListMap: TensorListMap): Promise {\n const mappedInputs = inputs.reduce((map, tensor, index) => {\n map[this.inputs[index].name] = tensor;\n return map;\n }, {} as NamedTensorMap);\n\n return this._executeAsync(\n mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap);\n }\n\n /**\n * When there are control flow nodes in the graph, the graph execution use\n * ExecutionContext to keep track of the frames and loop iterators.\n * @param inputs placeholder tensors for the graph.\n * @param context the execution context object for current execution.\n * @param outputNames Optional. output node name from the Tensorflow model,\n * if no outputs are specified, the default outputs of the model would be\n * used. You can inspect intermediate nodes of the model by adding them to\n * the outputs array.\n * @param isFunctionExecution Flag for executing a function.\n */\n private async executeWithControlFlow(\n inputs: NamedTensorMap, context: ExecutionContext, outputNames?: string[],\n isFunctionExecution?: boolean): Promise {\n const names = Object.keys(inputs);\n const inputNodes =\n names.map(name => this.graph.nodes[parseNodeName(name)[0]]);\n const outputNodeNames = outputNames.map(name => parseNodeName(name)[0]);\n const outputNodeNameSet = new Set(outputNodeNames);\n let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n\n // If no outputs are specified, then use the default outputs of the model.\n if (outputNodes.length === 0) {\n outputNodes = this._outputs;\n }\n\n const {usedNodes, missingInputs, dynamicNode, syncInputs} =\n getExecutionSubgraph(\n inputs, outputNodes, this.weightMap, this._initNodes);\n\n // First nodes to execute include inputNodes, weights, and initNodes.\n const stack: NodeWithContexts[] = [\n ...inputNodes, ...this.graph.weights, ...(this._initNodes || [])\n ].map(node => {\n return {node, contexts: context.currentContext};\n });\n const tensorsMap: NamedTensorsMap = {...this.weightMap};\n Object.keys(inputs).forEach(name => {\n const [nodeName, index] = parseNodeName(name);\n const tensors: Tensor[] = [];\n tensors[index] = inputs[name];\n tensorsMap[nodeName] = tensors;\n });\n const intermediateTensorConsumerCount: {[key: number]: number} = {};\n const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n const added: {[key: string]: boolean} = {};\n while (stack.length > 0) {\n const promises = this.processStack(\n inputNodes, stack, context, tensorsMap, added, tensorsToKeep,\n outputNodeNameSet, intermediateTensorConsumerCount, usedNodes);\n await Promise.all(promises);\n }\n if (dynamicNode == null && !isFunctionExecution) {\n console.warn(\n `This model execution did not contain any nodes with control flow ` +\n `or dynamic output shapes. You can use model.execute() instead.`);\n }\n const missingOutputs =\n outputNodes\n .filter(\n node => !isControlFlow(node) &&\n !getTensor(node.name, tensorsMap, context))\n .map(node => node.name);\n if (missingOutputs.length > 0) {\n let alternativeMsg = '';\n if (dynamicNode != null) {\n alternativeMsg =\n `Alternatively, to avoid the dynamic ops, use model.execute() ` +\n `and specify the inputs [${syncInputs}]`;\n }\n throw new Error(\n `Cannot compute the outputs [${missingOutputs}] from the provided ` +\n `inputs [${names}]. Consider providing the following inputs: ` +\n `[${missingInputs}]. ${alternativeMsg}`);\n }\n return tensorsMap;\n }\n\n private processStack(\n inputNodes: Node[], stack: NodeWithContexts[], context: ExecutionContext,\n tensorMap: NamedTensorsMap, added: {[key: string]: boolean},\n tensorsToKeep: Set, outputNodeNameSet: Set,\n intermediateTensorConsumerCount: {[key: number]: number},\n usedNodes: Set) {\n const promises: Array> = [];\n while (stack.length > 0) {\n const item = stack.pop();\n context.currentContext = item.contexts;\n let nodeName = '';\n // The tensor of the Enter op with isConstant set should be set\n // in the parent scope, so it will be available as constant for the\n // whole loop.\n if (item.node.op === 'Enter' &&\n getParamValue('isConstant', item.node, tensorMap, context)) {\n [nodeName] = getNodeNameAndIndex(item.node.name, context);\n }\n\n // only process nodes that are not in the tensorMap yet, this include\n // inputNodes and internal initNodes.\n if (tensorMap[item.node.name] == null) {\n const tensors =\n executeOp(item.node, tensorMap, context, this._resourceManager);\n if (!nodeName) {\n [nodeName] = getNodeNameAndIndex(item.node.name, context);\n }\n const currentContext = context.currentContext;\n if (util.isPromise(tensors)) {\n promises.push(tensors.then(t => {\n tensorMap[nodeName] = t;\n if (this.keepIntermediateTensors) {\n this.clonedTensorsMap[nodeName] = this.cloneTensorList(t);\n }\n context.currentContext = currentContext;\n this.checkTensorForDisposal(\n nodeName, item.node, tensorMap, context, tensorsToKeep,\n outputNodeNameSet, intermediateTensorConsumerCount);\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n return t;\n }));\n } else {\n tensorMap[nodeName] = tensors;\n if (this.keepIntermediateTensors) {\n this.clonedTensorsMap[nodeName] = this.cloneTensorList(tensors);\n }\n this.checkTensorForDisposal(\n nodeName, item.node, tensorMap, context, tensorsToKeep,\n outputNodeNameSet, intermediateTensorConsumerCount);\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n }\n } else {\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n }\n }\n return promises;\n }\n\n private processChildNodes(\n node: Node, stack: NodeWithContexts[], context: ExecutionContext,\n tensorMap: NamedTensorsMap, added: {[key: string]: boolean},\n usedNodes: Set) {\n node.children.forEach((childNode) => {\n const [nodeName, ] = getNodeNameAndIndex(childNode.name, context);\n if (added[nodeName] || !usedNodes.has(childNode.name)) {\n return;\n }\n // Merge op can be pushed if any of its inputs has value.\n if (childNode.op === 'Merge') {\n if (childNode.inputNames.some(name => {\n return !!getTensor(name, tensorMap, context);\n })) {\n added[nodeName] = true;\n stack.push({contexts: context.currentContext, node: childNode});\n }\n } else // Otherwise all inputs must to have value.\n if (childNode.inputNames.every(name => {\n return !!getTensor(name, tensorMap, context);\n })) {\n added[nodeName] = true;\n stack.push({contexts: context.currentContext, node: childNode});\n }\n });\n }\n\n /**\n * Releases the memory used by the weight tensors.\n */\n dispose() {\n Object.keys(this.weightMap)\n .forEach(\n key => this.weightMap[key].forEach(tensor => tensor.dispose()));\n }\n\n private checkInputShapeAndType(inputs: NamedTensorMap) {\n Object.keys(inputs).forEach(name => {\n const input = inputs[name];\n const [nodeName, ] = parseNodeName(name);\n const node = this.graph.nodes[nodeName];\n if (node.attrParams['shape'] && node.attrParams['shape'].value) {\n const shape = node.attrParams['shape'].value as number[];\n const match = shape.length === input.shape.length &&\n input.shape.every(\n (dim, index) => shape[index] === -1 || shape[index] === dim);\n util.assert(\n match,\n () => `The shape of dict['${node.name}'] provided in ` +\n `model.execute(dict) must be [${shape}], but was ` +\n `[${input.shape}]`);\n }\n if (node.attrParams['dtype'] && node.attrParams['dtype'].value) {\n util.assert(\n input.dtype === node.attrParams['dtype'].value as string,\n () => `The dtype of dict['${node.name}'] provided in ` +\n `model.execute(dict) must be ` +\n `${node.attrParams['dtype'].value}, but was ${input.dtype}`);\n }\n });\n }\n\n private mapInputs(inputs: NamedTensorMap) {\n const result: NamedTensorMap = {};\n for (const inputName in inputs) {\n const tensor = this._signature ?.inputs ?.[inputName];\n if (tensor != null) {\n result[tensor.name] = inputs[inputName];\n } else {\n result[inputName] = inputs[inputName];\n }\n }\n return result;\n }\n\n private checkInputs(inputs: NamedTensorMap) {\n const notInGraph = Object.keys(inputs).filter(name => {\n const [nodeName] = parseNodeName(name);\n return this.graph.nodes[nodeName] == null;\n });\n if (notInGraph.length > 0) {\n throw new Error(\n `The dict provided in model.execute(dict) has ` +\n `keys: [${notInGraph}] that are not part of graph`);\n }\n }\n\n private mapOutputs(outputs: string[]) {\n return outputs.map(name => {\n const tensor = this._signature ?.outputs ?.[name];\n if (tensor != null) {\n return tensor.name;\n }\n return name;\n }, {});\n }\n\n private checkOutputs(outputs: string[]): void {\n outputs.forEach(name => {\n const [normalizedName] = parseNodeName(name);\n if (!this.graph.nodes[normalizedName]) {\n throw new Error(`The output '${name}' is not found in the graph`);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {HashTableMap, NamedTensorMap} from '../data/types';\nimport {HashTable} from './hash_table';\n\n/**\n * Contains global resources of a model.\n */\nexport class ResourceManager {\n constructor(\n readonly hashTableNameToHandle: NamedTensorMap = {},\n readonly hashTableMap: HashTableMap = {}) {}\n\n /**\n * Register a `HashTable` in the resource manager.\n *\n * The `HashTable` can be retrieved by `resourceManager.getHashTableById`,\n * where id is the table handle tensor's id.\n *\n * @param name Op node name that creates the `HashTable`.\n * @param hashTable The `HashTable` to be added to resource manager.\n */\n addHashTable(name: string, hashTable: HashTable) {\n this.hashTableNameToHandle[name] = hashTable.handle;\n this.hashTableMap[hashTable.id] = hashTable;\n }\n\n /**\n * Get the table handle by node name.\n * @param name Op node name that creates the `HashTable`. This name is also\n * used in the inputs list of lookup and import `HashTable` ops.\n */\n getHashTableHandleByName(name: string) {\n return this.hashTableNameToHandle[name];\n }\n\n /**\n * Get the actual `HashTable` by its handle tensor's id.\n * @param id The id of the handle tensor.\n */\n getHashTableById(id: number): HashTable {\n return this.hashTableMap[id];\n }\n\n /**\n * Dispose `ResourceManager`, including its hashTables and tensors in them.\n */\n dispose() {\n for (const key in this.hashTableMap) {\n this.hashTableMap[key].clearAndClose();\n delete this.hashTableMap[key];\n }\n\n for (const name in this.hashTableNameToHandle) {\n this.hashTableNameToHandle[name].dispose();\n delete this.hashTableNameToHandle[name];\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {dispose, InferenceModel, io, ModelPredictConfig, NamedTensorMap, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\nimport {NamedTensorsMap, TensorInfo} from '../data/types';\nimport {OperationMapper} from '../operations/operation_mapper';\n\nimport {GraphExecutor} from './graph_executor';\nimport {ResourceManager} from './resource_manager';\n// tslint:disable-next-line: no-imports-from-dist\nimport {decodeWeightsStream} from '@tensorflow/tfjs-core/dist/io/io_utils';\n\nexport const TFHUB_SEARCH_PARAM = '?tfjs-format=file';\nexport const DEFAULT_MODEL_NAME = 'model.json';\ntype Url = string|io.IOHandler|io.IOHandlerSync;\ntype UrlIOHandler = T extends string ? io.IOHandler : T;\n\n/**\n * A `tf.GraphModel` is a directed, acyclic graph built from a\n * SavedModel GraphDef and allows inference execution.\n *\n * A `tf.GraphModel` can only be created by loading from a model converted from\n * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using\n * the command line converter tool and loaded via `tf.loadGraphModel`.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\nexport class GraphModel implements\n InferenceModel {\n private executor: GraphExecutor;\n private version = 'n/a';\n private handler: UrlIOHandler;\n private artifacts: io.ModelArtifacts;\n private initializer: GraphExecutor;\n private resourceIdToCapturedInput: {[key: number]: Tensor};\n private resourceManager: ResourceManager;\n private signature: tensorflow.ISignatureDef;\n private initializerSignature: tensorflow.ISignatureDef;\n private structuredOutputKeys: string[];\n private readonly io: typeof io;\n\n // Returns the version information for the tensorflow model GraphDef.\n get modelVersion(): string {\n return this.version;\n }\n\n get inputNodes(): string[] {\n return this.executor.inputNodes;\n }\n\n get outputNodes(): string[] {\n return this.executor.outputNodes;\n }\n\n get inputs(): TensorInfo[] {\n return this.executor.inputs;\n }\n\n get outputs(): TensorInfo[] {\n return this.executor.outputs;\n }\n\n get weights(): NamedTensorsMap {\n return this.executor.weightMap;\n }\n\n get metadata(): {} {\n return this.artifacts.userDefinedMetadata;\n }\n\n get modelSignature(): {} {\n return this.signature;\n }\n\n get modelStructuredOutputKeys(): {} {\n return this.structuredOutputKeys;\n }\n\n /**\n * @param modelUrl url for the model, or an `io.IOHandler`.\n * @param weightManifestUrl url for the weight file generated by\n * scripts/convert.py script.\n * @param requestOption options for Request, which allows to send credentials\n * and custom headers.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n */\n constructor(\n private modelUrl: ModelURL, private loadOptions: io.LoadOptions = {},\n tfio = io) {\n this.io = tfio;\n if (loadOptions == null) {\n this.loadOptions = {};\n }\n this.resourceManager = new ResourceManager();\n }\n\n private findIOHandler() {\n type IOHandler = UrlIOHandler;\n const path = this.modelUrl;\n if ((path as io.IOHandler).load != null) {\n // Path is an IO Handler.\n this.handler = path as IOHandler;\n } else if (this.loadOptions.requestInit != null) {\n this.handler = this.io.browserHTTPRequest(\n path as string, this.loadOptions) as IOHandler;\n } else {\n const handlers =\n this.io.getLoadHandlers(path as string, this.loadOptions);\n if (handlers.length === 0) {\n // For backward compatibility: if no load handler can be found,\n // assume it is a relative http path.\n handlers.push(\n this.io.browserHTTPRequest(path as string, this.loadOptions));\n } else if (handlers.length > 1) {\n throw new Error(\n `Found more than one (${handlers.length}) load handlers for ` +\n `URL '${[path]}'`);\n }\n this.handler = handlers[0] as IOHandler;\n }\n }\n\n /**\n * Loads the model and weight files, construct the in memory weight map and\n * compile the inference graph.\n */\n load(): UrlIOHandler extends io.IOHandlerSync? boolean:\n Promise {\n type IOHandler = UrlIOHandler;\n this.findIOHandler();\n if (this.handler.load == null) {\n throw new Error(\n 'Cannot proceed with model loading because the IOHandler provided ' +\n 'does not have the `load` method implemented.');\n }\n\n type Result =\n IOHandler extends io.IOHandlerSync ? boolean : Promise;\n\n const loadResult = this.handler.load() as ReturnType;\n if (util.isPromise(loadResult)) {\n return loadResult.then(artifacts => {\n if (artifacts.getWeightStream == null) {\n return this.loadSync(artifacts);\n }\n return this.loadStreaming(artifacts);\n }) as Result;\n }\n\n return this.loadSync(loadResult) as Result;\n }\n\n /**\n * Synchronously construct the in memory weight map and\n * compile the inference graph.\n *\n * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n */\n loadSync(artifacts: io.ModelArtifacts) {\n const weightMap = this.io.decodeWeights(\n artifacts.weightData, artifacts.weightSpecs);\n\n return this.loadWithWeightMap(artifacts, weightMap);\n }\n\n private async loadStreaming(artifacts: io.ModelArtifacts): Promise {\n if (artifacts.getWeightStream == null) {\n throw new Error('Model artifacts missing streamWeights function');\n }\n\n const weightMap = await decodeWeightsStream(\n artifacts.getWeightStream(), artifacts.weightSpecs);\n\n return this.loadWithWeightMap(artifacts, weightMap);\n }\n\n private loadWithWeightMap(artifacts: io.ModelArtifacts,\n weightMap: NamedTensorMap) {\n this.artifacts = artifacts;\n const graph = this.artifacts.modelTopology as tensorflow.IGraphDef;\n\n let signature = this.artifacts.signature;\n if (this.artifacts.userDefinedMetadata != null) {\n const metadata = this.artifacts.userDefinedMetadata;\n if (metadata.signature != null) {\n signature = metadata.signature;\n }\n\n if (metadata.structuredOutputKeys != null) {\n this.structuredOutputKeys = metadata.structuredOutputKeys as string[];\n }\n }\n this.signature = signature;\n\n this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;\n this.executor = new GraphExecutor(\n OperationMapper.Instance.transformGraph(graph, this.signature));\n this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);\n // Attach a model-level resourceManager to each executor to share resources,\n // such as `HashTable`.\n this.executor.resourceManager = this.resourceManager;\n\n if (artifacts.modelInitializer != null &&\n (artifacts.modelInitializer as tensorflow.IGraphDef).node != null) {\n const initializer =\n OperationMapper.Instance.transformGraph(artifacts.modelInitializer);\n this.initializer = new GraphExecutor(initializer);\n this.initializer.weightMap = this.executor.weightMap;\n // Attach a model-level resourceManager to the initializer, the\n // hashTables created from when executing the initializer will be stored\n // in the resourceManager.\n this.initializer.resourceManager = this.resourceManager;\n this.initializerSignature = artifacts.initializerSignature;\n }\n\n return true;\n }\n\n /**\n * Save the configuration and/or weights of the GraphModel.\n *\n * An `IOHandler` is an object that has a `save` method of the proper\n * signature defined. The `save` method manages the storing or\n * transmission of serialized data (\"artifacts\") that represent the\n * model's topology and weights onto or via a specific medium, such as\n * file downloads, local storage, IndexedDB in the web browser and HTTP\n * requests to a server. TensorFlow.js provides `IOHandler`\n * implementations for a number of frequently used saving mediums, such as\n * `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`\n * for more details.\n *\n * This method also allows you to refer to certain types of `IOHandler`s\n * as URL-like string shortcuts, such as 'localstorage://' and\n * 'indexeddb://'.\n *\n * Example 1: Save `model`'s topology and weights to browser [local\n * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);\n * then load it back.\n *\n * ```js\n * const modelUrl =\n * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n * const model = await tf.loadGraphModel(modelUrl);\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n *\n * const saveResults = await model.save('localstorage://my-model-1');\n *\n * const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');\n * console.log('Prediction from loaded model:');\n * model.predict(zeros).print();\n * ```\n *\n * @param handlerOrURL An instance of `IOHandler` or a URL-like,\n * scheme-based string shortcut for `IOHandler`.\n * @param config Options for saving the model.\n * @returns A `Promise` of `SaveResult`, which summarizes the result of\n * the saving, such as byte sizes of the saved artifacts for the model's\n * topology and weight values.\n *\n * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n */\n async save(handlerOrURL: io.IOHandler|string, config?: io.SaveConfig):\n Promise {\n if (typeof handlerOrURL === 'string') {\n const handlers = this.io.getSaveHandlers(handlerOrURL);\n if (handlers.length === 0) {\n throw new Error(\n `Cannot find any save handlers for URL '${handlerOrURL}'`);\n } else if (handlers.length > 1) {\n throw new Error(\n `Found more than one (${handlers.length}) save handlers for ` +\n `URL '${handlerOrURL}'`);\n }\n handlerOrURL = handlers[0];\n }\n if (handlerOrURL.save == null) {\n throw new Error(\n 'GraphModel.save() cannot proceed because the IOHandler ' +\n 'provided does not have the `save` attribute defined.');\n }\n\n return handlerOrURL.save(this.artifacts);\n }\n\n private addStructuredOutputNames(outputTensors: Tensor|Tensor[]) {\n if (this.structuredOutputKeys) {\n const outputTensorsArray =\n outputTensors instanceof Tensor ? [outputTensors] : outputTensors;\n const outputTensorMap: NamedTensorMap = {};\n\n outputTensorsArray.forEach(\n (outputTensor, i) => outputTensorMap[this.structuredOutputKeys[i]] =\n outputTensor);\n\n return outputTensorMap;\n }\n return outputTensors;\n }\n\n /**\n * Execute the inference for the input tensors.\n *\n * @param input The input tensors, when there is single input for the model,\n * inputs param should be a `tf.Tensor`. For models with mutliple inputs,\n * inputs params should be in either `tf.Tensor`[] if the input order is\n * fixed, or otherwise NamedTensorMap format.\n *\n * For model with multiple inputs, we recommend you use NamedTensorMap as the\n * input type, if you use `tf.Tensor`[], the order of the array needs to\n * follow the\n * order of inputNodes array. @see {@link GraphModel.inputNodes}\n *\n * You can also feed any intermediate nodes using the NamedTensorMap as the\n * input type. For example, given the graph\n * InputNode => Intermediate => OutputNode,\n * you can execute the subgraph Intermediate => OutputNode by calling\n * model.execute('IntermediateNode' : tf.tensor(...));\n *\n * This is useful for models that uses tf.dynamic_rnn, where the intermediate\n * state needs to be fed manually.\n *\n * For batch inference execution, the tensors for each input need to be\n * concatenated together. For example with mobilenet, the required input shape\n * is [1, 244, 244, 3], which represents the [batch, height, width, channel].\n * If we are provide a batched data of 100 images, the input tensor should be\n * in the shape of [100, 244, 244, 3].\n *\n * @param config Prediction configuration for specifying the batch size.\n * Currently the batch size option is ignored for graph model.\n *\n * @returns Inference result tensors. If the model is converted and it\n * originally had structured_outputs in tensorflow, then a NamedTensorMap\n * will be returned matching the structured_outputs. If no structured_outputs\n * are present, the output will be single `tf.Tensor` if the model has single\n * output node, otherwise Tensor[].\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig):\n Tensor|Tensor[]|NamedTensorMap {\n const outputTensors = this.execute(inputs, this.outputNodes);\n return this.addStructuredOutputNames(outputTensors);\n }\n\n /**\n * Execute the inference for the input tensors in async fashion, use this\n * method when your model contains control flow ops.\n *\n * @param input The input tensors, when there is single input for the model,\n * inputs param should be a `tf.Tensor`. For models with mutliple inputs,\n * inputs params should be in either `tf.Tensor`[] if the input order is\n * fixed, or otherwise NamedTensorMap format.\n *\n * For model with multiple inputs, we recommend you use NamedTensorMap as the\n * input type, if you use `tf.Tensor`[], the order of the array needs to\n * follow the\n * order of inputNodes array. @see {@link GraphModel.inputNodes}\n *\n * You can also feed any intermediate nodes using the NamedTensorMap as the\n * input type. For example, given the graph\n * InputNode => Intermediate => OutputNode,\n * you can execute the subgraph Intermediate => OutputNode by calling\n * model.execute('IntermediateNode' : tf.tensor(...));\n *\n * This is useful for models that uses tf.dynamic_rnn, where the intermediate\n * state needs to be fed manually.\n *\n * For batch inference execution, the tensors for each input need to be\n * concatenated together. For example with mobilenet, the required input shape\n * is [1, 244, 244, 3], which represents the [batch, height, width, channel].\n * If we are provide a batched data of 100 images, the input tensor should be\n * in the shape of [100, 244, 244, 3].\n *\n * @param config Prediction configuration for specifying the batch size.\n * Currently the batch size option is ignored for graph model.\n *\n * @returns A Promise of inference result tensors. If the model is converted\n * and it originally had structured_outputs in tensorflow, then a\n * NamedTensorMap will be returned matching the structured_outputs. If no\n * structured_outputs are present, the output will be single `tf.Tensor` if\n * the model has single output node, otherwise Tensor[].\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async predictAsync(\n inputs: Tensor|Tensor[]|NamedTensorMap,\n config?: ModelPredictConfig): Promise {\n const outputTensors = await this.executeAsync(inputs, this.outputNodes);\n return this.addStructuredOutputNames(outputTensors);\n }\n\n private normalizeInputs(inputs: Tensor|Tensor[]|\n NamedTensorMap): NamedTensorMap {\n if (!(inputs instanceof Tensor) && !Array.isArray(inputs)) {\n // The input is already a NamedTensorMap.\n const signatureInputs = this.signature?.inputs;\n if (signatureInputs != null) {\n for (const input in signatureInputs) {\n const tensor = signatureInputs[input];\n if (tensor.resourceId != null) {\n inputs[input] = this.resourceIdToCapturedInput[tensor.resourceId];\n }\n }\n }\n return inputs;\n }\n inputs = Array.isArray(inputs) ? inputs : [inputs];\n\n const numCapturedInputs =\n Object.keys(this.resourceIdToCapturedInput).length;\n if (inputs.length + numCapturedInputs !== this.inputNodes.length) {\n throw new Error(`Input tensor count mismatch, the graph model has ${\n this.inputNodes.length -\n numCapturedInputs} non-resource placeholders, while there are ${\n inputs.length} input tensors provided.`);\n }\n\n let inputIndex = 0;\n return this.inputNodes.reduce((map, inputName) => {\n const resourceId = this.signature?.inputs?.[inputName]?.resourceId;\n if (resourceId != null) {\n map[inputName] = this.resourceIdToCapturedInput[resourceId];\n } else {\n map[inputName] = (inputs as Tensor[])[inputIndex++];\n }\n return map;\n }, {} as NamedTensorMap);\n }\n\n private normalizeOutputs(outputs: string|string[]): string[] {\n outputs = outputs || this.outputNodes;\n return !Array.isArray(outputs) ? [outputs] : outputs;\n }\n\n private executeInitializerGraph() {\n if (this.initializer == null) {\n return [];\n }\n if (this.initializerSignature == null) {\n return this.initializer.execute({}, []);\n } else {\n return this.initializer.execute(\n {}, Object.keys(this.initializerSignature.outputs));\n }\n }\n\n private async executeInitializerGraphAsync() {\n if (this.initializer == null) {\n return [];\n }\n if (this.initializerSignature == null) {\n return this.initializer.executeAsync({}, []);\n } else {\n return this.initializer.executeAsync(\n {}, Object.keys(this.initializerSignature.outputs));\n }\n }\n\n private setResourceIdToCapturedInput(outputs: Tensor[]) {\n this.resourceIdToCapturedInput = {};\n\n if (this.initializerSignature) {\n const signatureOutputs = this.initializerSignature.outputs;\n const outputNames = Object.keys(signatureOutputs);\n for (let i = 0; i < outputNames.length; i++) {\n const outputName = outputNames[i];\n const tensorInfo = signatureOutputs[outputName];\n this.resourceIdToCapturedInput[tensorInfo.resourceId] = outputs[i];\n }\n }\n }\n\n /**\n * Executes inference for the model for given input tensors.\n * @param inputs tensor, tensor array or tensor map of the inputs for the\n * model, keyed by the input node names.\n * @param outputs output node name from the TensorFlow model, if no\n * outputs are specified, the default outputs of the model would be used.\n * You can inspect intermediate nodes of the model by adding them to the\n * outputs array.\n *\n * @returns A single tensor if provided with a single output or no outputs\n * are provided and there is only one default output, otherwise return a\n * tensor array. The order of the tensor array is the same as the outputs\n * if provided, otherwise the order of outputNodes attribute of the model.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n execute(inputs: Tensor|Tensor[]|NamedTensorMap, outputs?: string|string[]):\n Tensor|Tensor[] {\n if (this.resourceIdToCapturedInput == null) {\n this.setResourceIdToCapturedInput(this.executeInitializerGraph());\n }\n inputs = this.normalizeInputs(inputs);\n outputs = this.normalizeOutputs(outputs);\n const result = this.executor.execute(inputs, outputs);\n return result.length > 1 ? result : result[0];\n }\n\n /**\n * Executes inference for the model for given input tensors in async\n * fashion, use this method when your model contains control flow ops.\n * @param inputs tensor, tensor array or tensor map of the inputs for the\n * model, keyed by the input node names.\n * @param outputs output node name from the TensorFlow model, if no outputs\n * are specified, the default outputs of the model would be used. You can\n * inspect intermediate nodes of the model by adding them to the outputs\n * array.\n *\n * @returns A Promise of single tensor if provided with a single output or\n * no outputs are provided and there is only one default output, otherwise\n * return a tensor map.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async executeAsync(\n inputs: Tensor|Tensor[]|NamedTensorMap,\n outputs?: string|string[]): Promise {\n if (this.resourceIdToCapturedInput == null) {\n this.setResourceIdToCapturedInput(\n await this.executeInitializerGraphAsync());\n }\n inputs = this.normalizeInputs(inputs);\n outputs = this.normalizeOutputs(outputs);\n const result = await this.executor.executeAsync(inputs, outputs);\n return result.length > 1 ? result : result[0];\n }\n\n /**\n * Get intermediate tensors for model debugging mode (flag\n * KEEP_INTERMEDIATE_TENSORS is true).\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n getIntermediateTensors(): NamedTensorsMap {\n return this.executor.getIntermediateTensors();\n }\n\n /**\n * Dispose intermediate tensors for model debugging mode (flag\n * KEEP_INTERMEDIATE_TENSORS is true).\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n disposeIntermediateTensors() {\n this.executor.disposeIntermediateTensors();\n }\n\n private convertTensorMapToTensorsMap(map: NamedTensorMap): NamedTensorsMap {\n return Object.keys(map).reduce((newMap: NamedTensorsMap, key) => {\n newMap[key] = [map[key]];\n return newMap;\n }, {});\n }\n\n /**\n * Releases the memory used by the weight tensors and resourceManager.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n dispose() {\n this.executor.dispose();\n\n if (this.initializer) {\n this.initializer.dispose();\n if (this.resourceIdToCapturedInput) {\n dispose(this.resourceIdToCapturedInput);\n }\n }\n\n this.resourceManager.dispose();\n }\n}\n\n/**\n * Load a graph model given a URL to the model definition.\n *\n * Example of loading MobileNetV2 from a URL and making a prediction with a\n * zeros input:\n *\n * ```js\n * const modelUrl =\n * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n * const model = await tf.loadGraphModel(modelUrl);\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n *\n * Example of loading MobileNetV2 from a TF Hub URL and making a prediction\n * with a zeros input:\n *\n * ```js\n * const modelUrl =\n * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';\n * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n * @param modelUrl The url or an `io.IOHandler` that loads the model.\n * @param options Options for the HTTP request, which allows to send\n * credentials\n * and custom headers.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport async function loadGraphModel(\n modelUrl: string|io.IOHandler, options: io.LoadOptions = {},\n tfio = io): Promise {\n if (modelUrl == null) {\n throw new Error(\n 'modelUrl in loadGraphModel() cannot be null. Please provide a url ' +\n 'or an IOHandler that loads the model');\n }\n if (options == null) {\n options = {};\n }\n\n if (options.fromTFHub && typeof modelUrl === 'string') {\n modelUrl = getTFHubUrl(modelUrl);\n }\n const model = new GraphModel(modelUrl, options, tfio);\n await model.load();\n return model;\n}\n\n/**\n * Load a graph model given a synchronous IO handler with a 'load' method.\n *\n * @param modelSource The `io.IOHandlerSync` that loads the model, or the\n * `io.ModelArtifacts` that encode the model, or a tuple of\n * `[io.ModelJSON, ArrayBuffer]` of which the first element encodes the\n * model and the second contains the weights.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport function loadGraphModelSync(\n modelSource: io.IOHandlerSync|\n io.ModelArtifacts|[io.ModelJSON, /* Weights */ ArrayBuffer]):\n GraphModel {\n if (modelSource == null) {\n throw new Error(\n 'modelUrl in loadGraphModelSync() cannot be null. Please provide ' +\n 'model artifacts or an IOHandler that loads the model');\n }\n\n let ioHandler: io.IOHandlerSync;\n if (modelSource instanceof Array) {\n const [modelJSON, weights] = modelSource;\n if (!modelJSON) {\n throw new Error('modelJSON must be the first element of the array');\n }\n if (!weights || !(weights instanceof ArrayBuffer)) {\n throw new Error(\n 'An ArrayBuffer of weights must be the second element of' +\n ' the array');\n }\n if (!('modelTopology' in modelJSON)) {\n throw new Error('Model JSON is missing \\'modelTopology\\'');\n }\n if (!('weightsManifest' in modelJSON)) {\n throw new Error('Model JSON is missing \\'weightsManifest\\'');\n }\n\n const weightSpecs = io.getWeightSpecs(modelJSON.weightsManifest);\n const modelArtifacts =\n io.getModelArtifactsForJSONSync(modelJSON, weightSpecs, weights);\n ioHandler = io.fromMemorySync(modelArtifacts);\n } else if ('load' in modelSource) {\n // Then modelSource is already an IOHandlerSync.\n ioHandler = modelSource;\n } else if (\n 'modelTopology' in modelSource && 'weightSpecs' in modelSource &&\n 'weightData' in modelSource) {\n // modelSource is of type ModelArtifacts.\n ioHandler = io.fromMemorySync(modelSource);\n } else {\n throw new Error('Unknown model format');\n }\n\n const model = new GraphModel(ioHandler);\n model.load();\n return model;\n}\n\nfunction getTFHubUrl(modelUrl: string): string {\n if (!modelUrl.endsWith('/')) {\n modelUrl = (modelUrl) + '/';\n }\n return `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.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 */\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 = new Map(), containedIn: Set<{}> = new Set()): any|\n any[] {\n if (input == null) {\n return null;\n }\n if (typeof Blob === 'function' && input instanceof Blob) {\n return input.slice();\n }\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 if (input.__proto__) {\n mappedIterable.__proto__ = input.__proto__;\n }\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,\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 {\n const seen: Map = 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 let isTextDecoder = false;\n if (tf.env().get('IS_BROWSER')) {\n isTextDecoder = obj instanceof TextDecoder;\n } else {\n // tslint:disable-next-line:no-require-imports\n const {StringDecoder} = require('string_decoder');\n isTextDecoder = obj instanceof StringDecoder;\n }\n return obj != null && (!ArrayBuffer.isView(obj)) &&\n (Array.isArray(obj) ||\n (typeof obj === 'object' && !(obj instanceof tf.Tensor) &&\n !(obj instanceof Promise) && !isTextDecoder));\n}\n\n/**\n * Determine whether the argument can be converted to Tensor.\n *\n * Tensors, primitives, arrays, and TypedArrays all qualify; anything else does\n * not.\n *\n * @returns true if the argument can be converted to Tensor.\n */\n// tslint:disable-next-line:no-any\nexport function canTensorify(obj: any): boolean {\n return obj == null || isPrimitive(obj) || Array.isArray(obj) ||\n (typeof obj === 'object' && (obj instanceof tf.Tensor)) ||\n tf.util.isTypedArray(obj);\n}\n\n/**\n * Returns true if the given `value` is a primitive type. Otherwise returns\n * false. This is equivalant to node util.isPrimitive\n */\nfunction isPrimitive(value: any): boolean {\n return (\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function'));\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\nimport * as tf from '@tensorflow/tfjs-core';\nimport {deepMap, DeepMapResult, isIterable} from './deep_map';\n\nexport function deepClone(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 {\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(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 extends RingBuffer {\n private static INITIAL_CAPACITY = 32;\n\n /**\n * Constructs a `GrowingRingBuffer`.\n */\n constructor() {\n super(GrowingRingBuffer.INITIAL_CAPACITY);\n }\n\n override isFull() {\n return false;\n }\n\n override push(value: T) {\n if (super.isFull()) {\n this.expand();\n }\n super.push(value);\n }\n\n override 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(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>;\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(items: T[]): LazyIterator {\n return new ArrayIterator(items);\n}\n\n/**\n * Create a `LazyIterator` of incrementing integers.\n */\nexport function iteratorFromIncrementing(start: number): LazyIterator {\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(\n func: () =>\n IteratorResult| Promise>): LazyIterator {\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(\n baseIterators: LazyIterator>,\n baseErrorHandler?: (e: Error) => boolean): LazyIterator {\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(\n iteratorFunc: () => IteratorResult>, count: number,\n baseErrorHandler?: (e: Error) => boolean): LazyIterator {\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(\n iterators: IteratorContainer,\n mismatchMode: ZipMismatchMode = ZipMismatchMode.FAIL): LazyIterator {\n return new ZipIterator(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 {\n // This class implements AsyncIterator, 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 next(): Promise>;\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 {\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 {\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 {\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 {\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 {\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 {\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(transform: (value: T) => O): LazyIterator {\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(transform: (value: T) => Promise): LazyIterator {\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(transform: (value: T) => Promise): LazyIterator {\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(transform: (value: T) => O[]): LazyIterator {\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 {\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): Promise {\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 {\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 {\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,\n baseErrorHandler?: (e: Error) => boolean): LazyIterator {\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 {\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 {\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 {\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 {\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 {\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 extends LazyIterator {\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> {\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 extends LazyIterator {\n constructor(\n protected nextFn: () => IteratorResult| Promise>) {\n super();\n }\n\n summary() {\n return `Function call`;\n }\n\n async next(): Promise> {\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 extends LazyIterator {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise>;\n\n constructor(protected upstream: LazyIterator) {\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> {\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> {\n return this.upstream.next();\n }\n}\n\nclass SkipIterator extends LazyIterator {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise>;\n\n // Local state that should not be clobbered by out-of-order execution.\n count = 0;\n\n constructor(protected upstream: LazyIterator, 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> {\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> {\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 extends LazyIterator {\n count = 0;\n constructor(protected upstream: LazyIterator, protected maxCount: number) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Take`;\n }\n\n async next(): Promise> {\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 extends LazyIterator {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise>;\n\n constructor(\n protected upstream: LazyIterator, 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> {\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> {\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 extends LazyIterator {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise>;\n\n constructor(\n protected upstream: LazyIterator,\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> {\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> {\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 extends LazyIterator {\n constructor(\n protected upstream: LazyIterator,\n protected transform: (value: I) => O) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Map`;\n }\n\n async next(): Promise> {\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 extends LazyIterator {\n count = 0;\n constructor(\n protected upstream: LazyIterator,\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>;\n\n async next(): Promise> {\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> {\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 extends LazyIterator {\n constructor(\n protected upstream: LazyIterator,\n protected transform: (value: I) => Promise) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> AsyncMap`;\n }\n\n async next(): Promise> {\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 extends LazyIterator {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise>;\n\n // Local state that should not be clobbered by out-of-order execution.\n protected outputQueue: RingBuffer;\n\n constructor() {\n super();\n this.outputQueue = new GrowingRingBuffer();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n async next(): Promise> {\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 pump(): Promise;\n\n async serialNext(): Promise> {\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 extends OneToManyIterator {\n constructor(\n protected upstream: LazyIterator,\n protected transform: (value: I) => O[]) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Flatmap`;\n }\n\n async pump(): Promise {\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 extends LazyIterator {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise> = null;\n\n // Local state that should not be clobbered by out-of-order execution.\n private iterator: LazyIterator = null;\n private moreIterators: LazyIterator>;\n\n constructor(\n iterators: LazyIterator>,\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> {\n this.lastRead = this.readFromChain(this.lastRead);\n return this.lastRead;\n }\n\n private async readFromChain(lastRead: Promise>):\n Promise> {\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 extends LazyIterator {\n private count = 0;\n private currentPromise: Promise> = 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>):\n Promise> {\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> {\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 extends LazyIterator {\n protected buffer: RingBuffer>>;\n\n constructor(\n protected upstream: LazyIterator, protected bufferSize: number) {\n super();\n this.buffer = new RingBuffer>>(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> {\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 extends PrefetchIterator {\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>;\n\n // Local state that should not be clobbered by out-of-order execution.\n private upstreamExhausted = false;\n\n constructor(\n protected override upstream: LazyIterator, 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 override async next(): Promise> {\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> {\n // TODO(soergel): consider performance\n if (!this.upstreamExhausted) {\n this.refill();\n }\n while (!this.buffer.isEmpty()) {\n const chosenIndex = this.chooseIndex();\n const result = await this.buffer.shuffleExcise(chosenIndex);\n if (result.done) {\n this.upstreamExhausted = true;\n } else {\n this.refill();\n return result;\n }\n }\n return {value: null, done: true};\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\nimport * as tf from '@tensorflow/tfjs-core';\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>;\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 {\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 iterator(): Promise>;\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 0th 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 {\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): Dataset {\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 {\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 {\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(transform: (value: T) => O): Dataset {\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(transform: (value: T) => Promise):\n Dataset {\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 {\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 {\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 {\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 {\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 {\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(\n iteratorFn: () => Promise>,\n size: number = null): Dataset {\n return new class extends Dataset {\n override 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> {\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(items: T[]): Dataset {\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(datasets: DatasetContainer):\n Dataset {\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).size :\n Math.min(size, (datasets[i] as Dataset).size);\n }\n } else if (datasets instanceof Object) {\n for (const ds in datasets) {\n size = size == null ? (datasets[ds] as Dataset).size :\n Math.min(size, (datasets[ds] as Dataset).size);\n }\n }\n return datasetFromIteratorFn(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(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(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 {\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> {\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 {\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> {\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 {\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_BROWSER')) {\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 {\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> {\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 override toArray(): Promise {\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 {\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_BROWSER')) {\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 {\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(\n this.stream as unknown as MediaSource);\n }\n // Start the webcam video stream\n this.webcamVideoElement.play();\n\n this.isClosed = false;\n\n return new Promise(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> {\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 {\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 override toArray(): Promise {\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 iterator(): Promise;\n\n // TODO(soergel): consider chainable Dataset construction here\n}\n\n// TODO(soergel): consider convenience factory functions here\n// in combination with chainable source->dataset above, e.g.:\n// tf.data.url(...).asCsvDataset().shuffle().batch()\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\nimport {LazyIterator, OneToManyIterator} from './lazy_iterator';\n\nexport abstract class StringIterator extends LazyIterator {\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, 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, 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 {\n // A partial string at the end of an upstream chunk\n carryover = '';\n\n constructor(\n protected upstream: LazyIterator, protected separator: string) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Split('${this.separator}')`;\n }\n\n async pump(): Promise {\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) as string[];\n // Note the behavior: \" ab \".split(' ') === ['', 'ab', '']\n // Thus the carryover may be '' if the separator falls on a chunk\n // boundary; this produces the correct result.\n\n lines[0] = this.carryover + lines[0];\n for (const line of lines.slice(0, -1)) {\n this.outputQueue.push(line);\n }\n this.carryover = lines[lines.length - 1];\n\n return true;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\nimport {LazyIterator, OneToManyIterator} from './lazy_iterator';\nimport {StringIterator} from './string_iterator';\n\nexport abstract class ByteChunkIterator extends LazyIterator {\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, 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) {\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 {\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) {\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 {\n const chunkResult = await this.upstream.next();\n let chunk;\n if (chunkResult.done) {\n return false;\n } else {\n chunk = chunkResult.value;\n }\n\n let text: string;\n if (env().get('IS_BROWSER')) {\n text = this.decoder.decode(chunk, {stream: true});\n } else {\n text = this.decoder.write(Buffer.from(chunk.buffer));\n }\n this.outputQueue.push(text);\n return true;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\n// inspired by https://github.com/maxogden/filereader-stream\nimport {env, util} from '@tensorflow/tfjs-core';\nimport {FileElement} from '../types';\nimport {ByteChunkIterator} from './byte_chunk_iterator';\n\nexport interface FileChunkIteratorOptions {\n /** The byte offset at which to begin reading the File or Blob. Default 0. */\n offset?: number;\n /** The number of bytes to read at a time. Default 1MB. */\n chunkSize?: number;\n}\n\n/**\n * Provide a stream of chunks from a File, Blob, or Uint8Array.\n * @param file The source File, Blob or Uint8Array.\n * @param options Optional settings controlling file reading.\n * @returns a lazy Iterator of Uint8Arrays containing sequential chunks of the\n * input File, Blob or Uint8Array.\n */\nexport class FileChunkIterator extends ByteChunkIterator {\n offset: number;\n chunkSize: number;\n\n constructor(\n protected file: FileElement,\n protected options: FileChunkIteratorOptions = {}) {\n super();\n util.assert(\n (file instanceof Uint8Array) ||\n (env().get('IS_BROWSER') ?\n (file instanceof File || file instanceof Blob) :\n false),\n () => 'FileChunkIterator only supports File, Blob and Uint8Array ' +\n 'right now.');\n this.offset = options.offset || 0;\n // default 1MB chunk has tolerable perf on large files\n this.chunkSize = options.chunkSize || 1024 * 1024;\n }\n\n summary() {\n return `FileChunks ${this.file}`;\n }\n\n async next(): Promise> {\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((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 fetchFunc?: Function) {\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 (fetchFunc || 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.slice(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 {\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).slice(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 {\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(\n f: () => IteratorResult| Promise>): Dataset {\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(\n generator: () => Iterator| Promise>): Dataset {\n return datasetFromIteratorFn(async () => {\n const gen = await generator();\n return iteratorFromFunction(() => gen.next());\n });\n}\n\n/**\n * Create an iterator that generates `Tensor`s from webcam video stream. This\n * API 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 {\n return WebcamIterator.create(webcamVideoElement, webcamConfig);\n}\n\n/**\n * Create an iterator that generates 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 {\n return MicrophoneIterator.create(microphoneConfig);\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.0';\nexport {version};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nexport function assertNotComplex(\n tensor: TensorInfo|TensorInfo[], opName: string): void {\n if (!Array.isArray(tensor)) {\n tensor = [tensor];\n }\n tensor.forEach(t => {\n if (t != null) {\n util.assert(\n t.dtype !== 'complex64',\n () => `${\n opName} does not support complex64 tensors in the CPU backend.`);\n }\n });\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BackendTimingInfo, buffer, DataStorage, DataType, 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 {\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>;\n private firstUse = true;\n private static nextDataId = 0;\n private nextDataId(): number {\n return MathBackendCPU.nextDataId++;\n }\n\n constructor() {\n super();\n this.data = new DataStorage(this, engine());\n }\n\n override write(\n values: backend_util.BackendValues, shape: number[],\n dtype: DataType): DataId {\n if (this.firstUse) {\n this.firstUse = false;\n if (env().get('IS_NODE')) {\n backend_util.warn(\n '\\n============================\\n' +\n 'Hi, looks like you are running TensorFlow.js in ' +\n 'Node.js. To speed things up dramatically, install our node ' +\n 'backend, visit https://github.com/tensorflow/tfjs-node for more details. ' +\n '\\n============================');\n }\n }\n const dataId = {id: this.nextDataId()};\n\n this.data.set(dataId, {values, dtype, refCount: 1});\n\n return dataId;\n }\n\n /**\n * Create a data bucket in cpu backend.\n * @param shape Shape of the `TensorInfo`.\n * @param dtype DType of the `TensorInfo`.\n * @param values The value of the `TensorInfo` stored as a flattened array.\n */\n makeTensorInfo(\n shape: number[], dtype: DataType,\n values?: backend_util.BackendValues|string[]): TensorInfo {\n let outId;\n if (dtype === 'string' && values != null && values.length > 0 &&\n util.isString(values[0])) {\n const encodedValues =\n (values as unknown as string[]).map(d => util.encodeString(d));\n\n outId = this.write(encodedValues, shape, dtype);\n } else {\n outId = this.write(values as TypedArray, shape, dtype);\n }\n\n return {dataId: outId, shape, dtype};\n }\n\n /** Return refCount of a `TensorData`. */\n override refCount(dataId: DataId): number {\n if (this.data.has(dataId)) {\n const tensorData = this.data.get(dataId);\n return tensorData.refCount;\n }\n return 0;\n }\n\n /** Increase refCount of a `TensorData`. */\n override incRef(dataId: DataId): void {\n const tensorData = this.data.get(dataId);\n tensorData.refCount++;\n }\n\n /** Decrease refCount of a `TensorData`. */\n decRef(dataId: DataId): void {\n if (this.data.has(dataId)) {\n const tensorData = this.data.get(dataId);\n tensorData.refCount--;\n }\n }\n\n override move(\n dataId: DataId, values: backend_util.BackendValues, shape: number[],\n dtype: DataType, refCount: number): void {\n this.data.set(dataId, {values, dtype, refCount});\n }\n\n override numDataIds(): number {\n return this.data.numDataIds();\n }\n\n override async read(dataId: DataId): Promise {\n return this.readSync(dataId);\n }\n override readSync(dataId: DataId): backend_util.BackendValues {\n const {dtype, complexTensorInfos} = this.data.get(dataId);\n\n if (dtype === 'complex64') {\n const realValues =\n this.readSync(complexTensorInfos.real.dataId) as Float32Array;\n const imagValues =\n this.readSync(complexTensorInfos.imag.dataId) as Float32Array;\n return backend_util.mergeRealAndImagArrays(realValues, imagValues);\n }\n return util.convertBackendValuesAndArrayBuffer(\n this.data.get(dataId).values, dtype);\n }\n\n bufferSync(t: TensorInfo):\n TensorBuffer {\n const data = this.readSync(t.dataId);\n if (t.dtype === 'string') {\n try {\n // Decode the bytes into string.\n const strings = (data as Uint8Array[]).map(d => util.decodeString(d));\n return buffer(t.shape as ShapeMap[R], t.dtype, strings) as\n TensorBuffer;\n } catch {\n throw new Error('Failed to decode encoded string bytes into utf-8');\n }\n }\n return buffer(t.shape as ShapeMap[R], t.dtype, data as TypedArray) as\n TensorBuffer;\n }\n\n makeOutput(\n values: backend_util.BackendValues, shape: number[], dtype: DataType): T {\n return engine().makeTensorFromTensorInfo(\n this.makeTensorInfo(shape, dtype, values), this) as T;\n }\n\n /**\n * Dispose the memory if the dataId has 0 refCount. Return true if the memory\n * is released or memory is not managed in this backend, false if memory is\n * not cleared.\n * @param dataId\n * @oaram force Optional, remove the data regardless of refCount\n */\n override disposeData(dataId: DataId, force = false): boolean {\n if (this.data.has(dataId)) {\n this.data.get(dataId).refCount--;\n if (!force && this.data.get(dataId).refCount > 0) {\n return false;\n }\n\n const {complexTensorInfos} = this.data.get(dataId);\n\n if (complexTensorInfos != null) {\n this.disposeData(complexTensorInfos.real.dataId, true);\n this.disposeData(complexTensorInfos.imag.dataId, true);\n }\n\n this.data.delete(dataId);\n }\n return true;\n }\n\n disposeIntermediateTensorInfo(tensorInfo: TensorInfo): void {\n this.disposeData(tensorInfo.dataId);\n }\n\n override async time(f: () => void): Promise {\n const start = util.now();\n f();\n const kernelMs = util.now() - start;\n return {kernelMs};\n }\n\n override memory() {\n return {\n // Unreliable due to automatic gc. The numbers above are cumulative.\n unreliable: true,\n reasons:\n ['The reported memory is an upper bound. Due to automatic garbage ' +\n 'collection, the true allocated memory may be less.']\n };\n }\n\n where(condition: Tensor): Tensor2D {\n assertNotComplex([condition], 'where');\n\n const condVals = this.readSync(condition.dataId) as TypedArray;\n return whereImpl(condition.shape, condVals);\n }\n\n override dispose() {}\n\n override floatPrecision(): 16|32 {\n return 32;\n }\n\n /** Returns the smallest representable number. */\n override epsilon(): number {\n return super.epsilon();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Abs, AbsInputs, KernelConfig, KernelFunc, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function simpleAbsImpl(vals: TypedArray): Float32Array {\n const resultValues = new Float32Array(vals.length);\n for (let i = 0; i < vals.length; ++i) {\n resultValues[i] = Math.abs(vals[i]);\n }\n return resultValues;\n}\n\nexport const abs = (args: {inputs: AbsInputs, backend: MathBackendCPU}) => {\n const {x} = args.inputs;\n const cpuBackend = args.backend;\n\n assertNotComplex(x, 'abs');\n\n let resultValues = new Float32Array(util.sizeFromShape(x.shape));\n const values = cpuBackend.data.get(x.dataId).values as TypedArray;\n resultValues = simpleAbsImpl(values);\n\n return cpuBackend.makeOutput(resultValues, x.shape, x.dtype);\n};\n\nexport const absConfig: KernelConfig = {\n kernelName: Abs,\n backendName: 'cpu',\n kernelFunc: abs as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, DataValues, NumericDataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {SimpleBinaryKernelImpl, SimpleBinaryOperation} from './binary_types';\n\n/**\n * Template that creates implementation for binary ops. Supports broadcast.\n */\nexport function createSimpleBinaryKernelImpl(op: SimpleBinaryOperation):\n SimpleBinaryKernelImpl {\n return (aShape: number[], bShape: number[], aVals: DataValues,\n bVals: DataValues, dtype: DataType): [TypedArray, number[]] => {\n const newShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n\n const resultRank = newShape.length;\n const resultStrides = util.computeStrides(newShape);\n const resultSize = util.sizeFromShape(newShape);\n\n const result =\n util.getTypedArrayFromDType(dtype as NumericDataType, resultSize);\n\n const aRank = aShape.length;\n const bRank = bShape.length;\n\n const aStrides = util.computeStrides(aShape);\n const bStrides = util.computeStrides(bShape);\n\n const aBroadcastDims = backend_util.getBroadcastDims(aShape, newShape);\n const bBroadcastDims = backend_util.getBroadcastDims(bShape, newShape);\n\n if (aBroadcastDims.length + bBroadcastDims.length === 0) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);\n }\n } else {\n for (let i = 0; i < result.length; ++i) {\n const loc = util.indexToLoc(i, resultRank, resultStrides);\n\n const aLoc = loc.slice(-aRank);\n aBroadcastDims.forEach(d => aLoc[d] = 0);\n const aIndex = util.locToIndex(aLoc, aRank, aStrides);\n\n const bLoc = loc.slice(-bRank);\n bBroadcastDims.forEach(d => bLoc[d] = 0);\n const bIndex = util.locToIndex(bLoc, bRank, bStrides);\n\n result[i] = op(aVals[aIndex], bVals[bIndex]);\n }\n }\n\n return [result, newShape];\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Complex, ComplexInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function complex(args: {inputs: ComplexInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {real, imag} = inputs;\n\n const realVals = backend.data.get(real.dataId).values as TypedArray;\n const imagVals = backend.data.get(imag.dataId).values as TypedArray;\n\n const complexInfo = backend.makeTensorInfo(real.shape, 'complex64');\n\n const complex = backend.data.get(complexInfo.dataId);\n\n // The complex tensor owns the underlying real and imag tensorInfos, only the\n // complex tensor tracks refCount, when complexData is disposed the\n // underlying tensorData will be disposed.\n complex.complexTensorInfos = {\n real: backend.makeTensorInfo(real.shape, 'float32', realVals),\n imag: backend.makeTensorInfo(imag.shape, 'float32', imagVals)\n };\n\n return complexInfo;\n}\n\nexport const complexConfig: KernelConfig = {\n kernelName: Complex,\n backendName: 'cpu',\n kernelFunc: complex as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TensorInfo, util} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from '../backend_cpu';\nimport {complex} from '../kernels/Complex';\n\n/**\n * Generates a tensorInfo with all zeros value.\n * @param backend cpu backend.\n * @param shape Shape for the zeros tensor.\n * @param dtype Optional. If set, the result has this dtype.\n */\nexport function zeros(\n backend: MathBackendCPU, shape: number[],\n dtype: DataType = 'float32'): TensorInfo {\n if (dtype === 'complex64') {\n const real = zeros(backend, shape, 'float32');\n const imag = zeros(backend, shape, 'float32');\n\n return complex({inputs: {real, imag}, backend});\n }\n\n const values = util.makeZerosTypedArray(util.sizeFromShape(shape), dtype);\n\n return backend.makeTensorInfo(shape, dtype, values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Identity, IdentityInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function identity(\n args: {inputs: IdentityInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n backend.incRef(x.dataId);\n\n return {dataId: x.dataId, shape: x.shape, dtype: x.dtype};\n}\n\nexport const identityConfig: KernelConfig = {\n kernelName: Identity,\n backendName: 'cpu',\n kernelFunc: identity as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Real, RealInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function real(args: {inputs: RealInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n const real = backend.data.get(input.dataId).complexTensorInfos.real;\n const realVal = backend.data.get(real.dataId).values;\n\n // When complex tensor is disposed, its underlying parts will be disposed too.\n // Make new tensor out of the real value of the complex. This makes sure the\n // value is still accessible even if complex tensor is disposed.\n return backend.makeTensorInfo(real.shape, real.dtype, realVal);\n}\n\nexport const realConfig: KernelConfig = {\n kernelName: Real,\n backendName: 'cpu',\n kernelFunc: real as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Cast, CastAttrs, CastInputs, DataType, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {zeros} from '../utils/zeros_impl';\n\nimport {complex} from './Complex';\nimport {identity} from './Identity';\nimport {real} from './Real';\n\nexport function castImpl(\n values: TypedArray, shape: number[], inputType: DataType,\n dtype: DataType): [number[], DataType, TypedArray] {\n if (dtype === 'int32') {\n const resultValues = Int32Array.from(values);\n return [shape, 'int32', resultValues];\n }\n\n if (dtype === 'bool') {\n // This is essentially the result of notEqual(x, 0). We avoid using\n // kernel notEqual to avoid circular dependency, i.e. binary_utils ->\n // cast -> notEqual -> binary_utils.\n const zero = util.toTypedArray([0], inputType);\n\n const [resultData, resultShape] = createSimpleBinaryKernelImpl(\n (a, b) => (a !== b) ? 1 : 0)(shape, [], values, zero, 'bool');\n\n return [resultShape, 'bool', resultData];\n }\n throw new Error(`Error in Cast: failed to cast ${inputType} to ${dtype}`);\n}\n\nexport function cast(\n args: {inputs: CastInputs, backend: MathBackendCPU, attrs: CastAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dtype} = attrs;\n\n // Casting to complex64.\n if (dtype === 'complex64') {\n if (x.dtype === 'complex64') {\n return identity({inputs: {x}, backend});\n }\n\n const zerosTensorInfo = zeros(backend, x.shape, x.dtype);\n const floatX = cast({inputs: {x}, backend, attrs: {dtype: 'float32'}});\n\n const result =\n complex({inputs: {real: floatX, imag: zerosTensorInfo}, backend});\n\n backend.disposeIntermediateTensorInfo(zerosTensorInfo);\n backend.disposeIntermediateTensorInfo(floatX);\n\n return result;\n }\n\n // Casting from complex64\n if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const result = cast({inputs: {x: realPart}, backend, attrs: {dtype}});\n\n backend.disposeIntermediateTensorInfo(realPart);\n\n return result;\n }\n\n if (!util.hasEncodingLoss(x.dtype, dtype)) {\n // We don't change the underlying data, since we cast to higher\n // precision.\n const result = identity({inputs: {x}, backend});\n return {dataId: result.dataId, shape: result.shape, dtype};\n }\n\n const values = backend.data.get(x.dataId).values as TypedArray;\n const [resultShape, resultType, resultData] =\n castImpl(values, x.shape, x.dtype, dtype);\n return backend.makeTensorInfo(resultShape, resultType, resultData);\n}\n\nexport const castConfig: KernelConfig = {\n kernelName: Cast,\n backendName: 'cpu',\n kernelFunc: cast as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BinaryInputs, DataType, KernelFunc, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {cast} from '../kernels/Cast';\nimport {complex} from '../kernels/Complex';\n\nimport {ComplexBinaryKernelImpl, ComplexBinaryOperation, SimpleBinaryKernelImpl} from './binary_types';\n\n/**\n * Template that creates a `KernelFunc` for binary ops.\n * @param name Kernel name.\n * @param binaryKernelImpl A `SimpleBinaryKernelImpl` for the kernel.\n * @param binaryKernelComplexImpl Optional. If exists, represents a\n * `ComplexBinaryKernelImpl` for the kernel, will be used when input dtype\n * is `complex64`.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n * result has the same dtype as the first input. This is mainly used in\n * comparison kernels, such as Equal, Less, Greater, etc.\n */\nexport function binaryKernelFunc(\n name: string, simpleImpl: SimpleBinaryKernelImpl,\n complexImpl?: ComplexBinaryKernelImpl, dtype?: DataType): KernelFunc {\n if (complexImpl == null) {\n return ({inputs, backend}) => {\n const {a, b} = inputs as BinaryInputs;\n const cpuBackend = backend as MathBackendCPU;\n\n assertNotComplex([a, b], name);\n\n const aVals = cpuBackend.data.get(a.dataId).values as TypedArray;\n const bVals = cpuBackend.data.get(b.dataId).values as TypedArray;\n\n const decodedAVals = a.dtype === 'string' ?\n // tslint:disable-next-line: no-any\n backend_util.fromUint8ToStringArray(aVals as any as Uint8Array[]) :\n aVals;\n const decodedBVals = a.dtype === 'string' ?\n // tslint:disable-next-line: no-any\n backend_util.fromUint8ToStringArray(bVals as any as Uint8Array[]) :\n bVals;\n const $dtype = dtype || a.dtype;\n\n const [resultData, resultShape] =\n simpleImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype);\n\n return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);\n };\n }\n\n return ({inputs, backend}) => {\n const {a, b} = inputs as BinaryInputs;\n const cpuBackend = backend as MathBackendCPU;\n\n if (a.dtype === 'complex64' || b.dtype === 'complex64') {\n const $aComplex = cast(\n {inputs: {x: a}, backend: cpuBackend, attrs: {dtype: 'complex64'}});\n\n const $aComplexVals = cpuBackend.data.get($aComplex.dataId);\n\n const aReal = $aComplexVals.complexTensorInfos.real;\n const aImag = $aComplexVals.complexTensorInfos.imag;\n\n const aRealVals =\n cpuBackend.data.get(aReal.dataId).values as Float32Array;\n const aImagVals =\n cpuBackend.data.get(aImag.dataId).values as Float32Array;\n\n const $bComplex = cast(\n {inputs: {x: b}, backend: cpuBackend, attrs: {dtype: 'complex64'}});\n\n const $bComplexVals = cpuBackend.data.get($bComplex.dataId);\n\n const bReal = $bComplexVals.complexTensorInfos.real;\n const bImag = $bComplexVals.complexTensorInfos.imag;\n\n const bRealVals =\n cpuBackend.data.get(bReal.dataId).values as Float32Array;\n const bImagVals =\n cpuBackend.data.get(bImag.dataId).values as Float32Array;\n\n const [resultRealData, resultImagData, resultShape] = complexImpl(\n a.shape, b.shape, aRealVals, aImagVals, bRealVals, bImagVals);\n\n const resultReal =\n cpuBackend.makeTensorInfo(resultShape, 'float32', resultRealData);\n\n const resultImag =\n cpuBackend.makeTensorInfo(resultShape, 'float32', resultImagData);\n\n const result = complex(\n {inputs: {real: resultReal, imag: resultImag}, backend: cpuBackend});\n\n cpuBackend.disposeIntermediateTensorInfo($aComplex);\n cpuBackend.disposeIntermediateTensorInfo($bComplex);\n cpuBackend.disposeIntermediateTensorInfo(resultReal);\n cpuBackend.disposeIntermediateTensorInfo(resultImag);\n\n return result;\n } else {\n const aVals = cpuBackend.data.get(a.dataId).values as TypedArray;\n const bVals = cpuBackend.data.get(b.dataId).values as TypedArray;\n\n const $dtype = dtype || a.dtype;\n\n const [resultData, resultShape] =\n simpleImpl(a.shape, b.shape, aVals, bVals, $dtype);\n\n return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);\n }\n };\n}\n\n/**\n * Template that creates the complex type implementation for binary ops.\n * Supports broadcast.\n */\nexport function createComplexBinaryKernelImpl(op: ComplexBinaryOperation):\n ComplexBinaryKernelImpl {\n return (aShape: number[], bShape: number[], aRealVals: Float32Array,\n aImagVals: Float32Array, bRealVals: Float32Array,\n bImagVals: Float32Array): [TypedArray, TypedArray, number[]] => {\n const resultShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n const resultSize = util.sizeFromShape(resultShape);\n const resultRank = resultShape.length;\n const resultStrides = util.computeStrides(resultShape);\n\n const resultRealVals = util.getTypedArrayFromDType('float32', resultSize);\n const resultImagVals = util.getTypedArrayFromDType('float32', resultSize);\n\n const aBroadcastDims = backend_util.getBroadcastDims(aShape, resultShape);\n const bBroadcastDims = backend_util.getBroadcastDims(bShape, resultShape);\n\n const aVals = backend_util.mergeRealAndImagArrays(aRealVals, aImagVals);\n const bVals = backend_util.mergeRealAndImagArrays(bRealVals, bImagVals);\n\n const aRank = aShape.length;\n const aStrides = util.computeStrides(aShape);\n\n const bRank = bShape.length;\n const bStrides = util.computeStrides(bShape);\n\n if (aBroadcastDims.length + bBroadcastDims.length === 0) {\n for (let i = 0; i < resultRealVals.length; i++) {\n const aIdx = i % aVals.length;\n const bIdx = i % bVals.length;\n\n const result =\n op(aVals[aIdx * 2], aVals[aIdx * 2 + 1], bVals[bIdx * 2],\n bVals[bIdx * 2 + 1]);\n\n resultRealVals[i] = result.real;\n resultImagVals[i] = result.imag;\n }\n } else {\n for (let i = 0; i < resultRealVals.length; i++) {\n const loc = util.indexToLoc(i, resultRank, resultStrides);\n\n const aLoc = loc.slice(-aRank);\n aBroadcastDims.forEach(d => aLoc[d] = 0);\n const aIndex = util.locToIndex(aLoc, aRank, aStrides);\n\n const bLoc = loc.slice(-bRank);\n bBroadcastDims.forEach(d => bLoc[d] = 0);\n const bIndex = util.locToIndex(bLoc, bRank, bStrides);\n\n const opResult =\n op(aVals[aIndex * 2], aVals[aIndex * 2 + 1], bVals[bIndex * 2],\n bVals[bIndex * 2 + 1]);\n\n resultRealVals[i] = opResult.real;\n resultImagVals[i] = opResult.imag;\n }\n }\n return [resultRealVals, resultImagVals, resultShape];\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Add, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc, createComplexBinaryKernelImpl} from '../utils/binary_utils';\n\nexport const addImpl =\n createSimpleBinaryKernelImpl(((a: number, b: number) => a + b));\nexport const addComplexImpl =\n createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n return {real: aReal + bReal, imag: aImag + bImag};\n }));\n\nexport const add = binaryKernelFunc(Add, addImpl, addComplexImpl);\n\nexport const addConfig: KernelConfig = {\n kernelName: Add,\n backendName: 'cpu',\n kernelFunc: add\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, DataType, Rank, TensorBuffer, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function bincountImpl(\n xVals: TypedArray, weightsVals: TypedArray, weightsDtype: DataType,\n weightsShape: number[], size: number): TypedArray {\n const weightsSize = util.sizeFromShape(weightsShape);\n const outVals = util.makeZerosTypedArray(size, weightsDtype) as TypedArray;\n\n for (let i = 0; i < xVals.length; i++) {\n const value = xVals[i];\n if (value < 0) {\n throw new Error('Input x must be non-negative!');\n }\n\n if (value >= size) {\n continue;\n }\n\n if (weightsSize > 0) {\n outVals[value] += weightsVals[i];\n } else {\n outVals[value] += 1;\n }\n }\n\n return outVals;\n}\n\nexport function bincountReduceImpl(\n xBuf: TensorBuffer, weightsBuf: TensorBuffer, size: number,\n binaryOutput = false): TensorBuffer {\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;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BitwiseAnd, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const bitwiseAndImpl =\n createSimpleBinaryKernelImpl(((a: number, b: number) => a & b));\n\nexport const bitwiseAnd = binaryKernelFunc(BitwiseAnd, bitwiseAndImpl);\n\nexport const bitwiseAndConfig: KernelConfig = {\n kernelName: BitwiseAnd,\n backendName: 'cpu',\n kernelFunc: bitwiseAnd\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {util} from '@tensorflow/tfjs-core';\n\nimport {SimpleUnaryImpl, SimpleUnaryOperation} from './unary_types';\n\n/**\n * Template that creates implementation for unary op.\n */\nexport function createSimpleUnaryImpl(op: SimpleUnaryOperation):\n SimpleUnaryImpl {\n return (values, dtype, attrs) => {\n const newValues =\n util.getArrayFromDType(dtype, values.length);\n for (let i = 0; i < values.length; ++i) {\n newValues[i] = op(values[i], attrs);\n }\n return newValues;\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataTypeFor, KernelFunc, UnaryInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {createSimpleUnaryImpl} from './unary_impl';\n\nimport {SimpleUnaryImpl, SimpleUnaryOperation} from './unary_types';\n\n/**\n * Template that creates a `KernelFunc` for unary ops.\n * @param name Kernel name.\n * @param op A `SimpleUnaryOperation` for the kernel.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n * result has the same dtype as the input. This is mainly used in certain\n * kernels that return bool type, such as isFinite, isInf, etc.\n */\nexport function unaryKernelFunc(\n name: string, op: SimpleUnaryOperation,\n dtype?: DataTypeFor): KernelFunc {\n\n const impl = createSimpleUnaryImpl(op);\n\n return unaryKernelFuncFromImpl(name, impl, dtype);\n}\n\n/**\n * Template that creates a `KernelFunc` for unary ops from the given\n * `SimpleUnaryImpl`..\n * @param name Kernel name.\n * @param unaryImpl A `SimpleUnaryImpl` that implements the op.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n * result has the same dtype as the input. This is mainly used in certain\n * kernels that return bool type, such as isFinite, isInf, etc.\n */\nexport function unaryKernelFuncFromImpl(\n name: string, unaryImpl: SimpleUnaryImpl,\n dtype?: DataTypeFor): KernelFunc {\n\n return ({inputs, attrs, backend}) => {\n const {x} = inputs as UnaryInputs;\n assertNotComplex(x, name);\n\n const cpuBackend = backend as MathBackendCPU;\n const values = cpuBackend.data.get(x.dataId).values;\n let decoded: ArrayLike;\n if (x.dtype === 'string') {\n if (!Array.isArray(values)) {\n throw new Error('String tensor\\'s value was not an instance of Array');\n }\n decoded = backend_util.fromUint8ToStringArray(values) as unknown as\n ArrayLike;\n } else {\n decoded = values as unknown as ArrayLike;\n }\n\n const $dtype = dtype || x.dtype as DataTypeFor;\n const newValues = unaryImpl(decoded, $dtype, attrs);\n return cpuBackend.makeTensorInfo(x.shape, $dtype, newValues);\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Ceil, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const ceilImpl = createSimpleUnaryImpl((xi) => Math.ceil(xi));\nexport const ceil = unaryKernelFuncFromImpl(Ceil, ceilImpl);\n\nexport const ceilConfig: KernelConfig = {\n kernelName: Ceil,\n backendName: 'cpu',\n kernelFunc: ceil,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BackendValues, DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function concatImpl(\n inputs: Array<{vals: BackendValues, shape: number[]}>, outShape: number[],\n dtype: DataType, simplyConcat: boolean): TypedArray|string[] {\n const outVals = util.getArrayFromDType(dtype, util.sizeFromShape(outShape));\n\n if (simplyConcat && dtype !== 'string') {\n // Use built-in TypedArray.set() method for speed.\n let offset = 0;\n inputs.forEach(input => {\n const size = util.sizeFromShape(input.shape);\n\n (outVals as TypedArray).set(input.vals as TypedArray, offset);\n offset += size;\n });\n } else {\n let colOffset = 0;\n\n inputs.forEach(input => {\n const decodedData = dtype === 'string' ?\n backend_util.fromUint8ToStringArray(input.vals as Uint8Array[]) :\n input.vals as TypedArray;\n\n let tIdx = 0;\n\n for (let row = 0; row < input.shape[0]; ++row) {\n const resIdx = row * outShape[1] + colOffset;\n for (let col = 0; col < input.shape[1]; ++col) {\n outVals[resIdx + col] = decodedData[tIdx++];\n }\n }\n\n colOffset += input.shape[1];\n });\n }\n\n return outVals;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Equal, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const equalImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a === b) ? 1 : 0);\nexport const equal =\n binaryKernelFunc(Equal, equalImpl, null /* complexImpl */, 'bool');\n\nexport const equalConfig: KernelConfig = {\n kernelName: Equal,\n backendName: 'cpu',\n kernelFunc: equal\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Exp, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const expImpl = createSimpleUnaryImpl((xi) => Math.exp(xi));\nexport const exp = unaryKernelFuncFromImpl(Exp, expImpl, 'float32');\n\nexport const expConfig: KernelConfig = {\n kernelName: Exp,\n backendName: 'cpu',\n kernelFunc: exp,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Expm1, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const expm1Impl = createSimpleUnaryImpl((xi) => Math.expm1(xi));\nexport const expm1 = unaryKernelFuncFromImpl(Expm1, expm1Impl);\n\nexport const expm1Config: KernelConfig = {\n kernelName: Expm1,\n backendName: 'cpu',\n kernelFunc: expm1,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Floor, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const floorImpl = createSimpleUnaryImpl((xi) => Math.floor(xi));\nexport const floor = unaryKernelFuncFromImpl(Floor, floorImpl);\n\nexport const floorConfig: KernelConfig = {\n kernelName: Floor,\n backendName: 'cpu',\n kernelFunc: floor,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FloorDiv, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const floorDivImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => Math.floor(a / b));\nexport const floorDiv =\n binaryKernelFunc(FloorDiv, floorDivImpl, null /* complexImpl */, 'int32');\n\nexport const floorDivConfig: KernelConfig = {\n kernelName: FloorDiv,\n backendName: 'cpu',\n kernelFunc: floorDiv\n};\n","/**\n * @license\n * Copyright 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(\n indicesData: TypedArray, paramsBuf: TensorBuffer, dtype: DataType,\n numSlices: number, sliceRank: number, sliceSize: number, strides: number[],\n paramsShape: number[], paramsSize: number): TensorBuffer {\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;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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(\n xBuf: TensorBuffer, indicesBuf: TensorBuffer,\n flattenOutputShape: number[]): TensorBuffer {\n const outBuf = buffer(flattenOutputShape, xBuf.dtype);\n for (let i = 0; i < outBuf.size; ++i) {\n const newLoc = outBuf.indexToLoc(i);\n\n const originalLoc: number[] = newLoc.slice();\n const batchIdx = originalLoc[0];\n const indicesIdx = originalLoc[2];\n const indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);\n originalLoc[2] = indicesBuf.values[indicesIndex] as number;\n\n const originalIndex = xBuf.locToIndex(originalLoc);\n\n if (0 <= originalIndex && originalIndex < xBuf.values.length) {\n outBuf.values[i] = xBuf.values[originalIndex];\n } // Else, index is out of bounds, so leave the default zero val in outBuf.\n }\n\n return outBuf as TensorBuffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Greater, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const greaterImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a > b) ? 1 : 0);\nexport const greater =\n binaryKernelFunc(Greater, greaterImpl, null /* complexImpl */, 'bool');\n\nexport const greaterConfig: KernelConfig = {\n kernelName: Greater,\n backendName: 'cpu',\n kernelFunc: greater\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GreaterEqual, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const greaterEqualImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a >= b) ? 1 : 0);\nexport const greaterEqual = binaryKernelFunc(\n GreaterEqual, greaterEqualImpl, null /* complexImpl */, 'bool');\n\nexport const greaterEqualConfig: KernelConfig = {\n kernelName: GreaterEqual,\n backendName: 'cpu',\n kernelFunc: greaterEqual\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Less} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const lessImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a < b) ? 1 : 0);\nexport const less =\n binaryKernelFunc(Less, lessImpl, null /* complexImpl */, 'bool');\n\nexport const lessConfig: KernelConfig = {\n kernelName: Less,\n backendName: 'cpu',\n kernelFunc: less\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, LessEqual} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const lessEqualImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a <= b) ? 1 : 0);\nexport const lessEqual =\n binaryKernelFunc(LessEqual, lessEqualImpl, null /* complexImpl */, 'bool');\n\nexport const lessEqualConfig: KernelConfig = {\n kernelName: LessEqual,\n backendName: 'cpu',\n kernelFunc: lessEqual\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function linSpaceImpl(\n start: number, stop: number, num: number): TypedArray {\n const step = (stop - start) / (num - 1);\n\n const values = util.makeZerosTypedArray(num, 'float32');\n values[0] = start;\n for (let i = 1; i < values.length; i++) {\n values[i] = values[i - 1] + step;\n }\n\n return values;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Log} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const logImpl = createSimpleUnaryImpl((xi) => Math.log(xi));\nexport const log = unaryKernelFuncFromImpl(Log, logImpl);\n\nexport const logConfig: KernelConfig = {\n kernelName: Log,\n backendName: 'cpu',\n kernelFunc: log,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, NumericDataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function maxImpl(\n aVals: TypedArray, reduceSize: number, outShape: number[],\n dtype: DataType): TypedArray {\n const vals = util.getTypedArrayFromDType(\n dtype as NumericDataType, util.sizeFromShape(outShape));\n\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let max = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (Number.isNaN(value) ||\n value > max) { // comparison with NaN always return false\n max = value;\n }\n }\n vals[i] = max;\n }\n return vals;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Maximum} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const maximumImpl = createSimpleBinaryKernelImpl(\n ((aValue, bValue) => Math.max(aValue as number, bValue as number)));\nexport const maximum = binaryKernelFunc(Maximum, maximumImpl);\n\nexport const maximumConfig: KernelConfig = {\n kernelName: Maximum,\n backendName: 'cpu',\n kernelFunc: maximum\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Minimum} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const minimumImpl = createSimpleBinaryKernelImpl(\n ((aValue, bValue) => Math.min(aValue as number, bValue as number)));\nexport const minimum = binaryKernelFunc(Minimum, minimumImpl);\n\nexport const minimumConfig: KernelConfig = {\n kernelName: Minimum,\n backendName: 'cpu',\n kernelFunc: minimum\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Multiply} from '@tensorflow/tfjs-core';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc, createComplexBinaryKernelImpl} from '../utils/binary_utils';\n\nexport const multiplyImpl = createSimpleBinaryKernelImpl(\n ((aValue: number, bValue: number) => aValue * bValue));\nexport const multiplyComplexImpl =\n createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n return {\n real: aReal * bReal - aImag * bImag,\n imag: aReal * bImag + aImag * bReal\n };\n }));\n\nexport const multiply =\n binaryKernelFunc(Multiply, multiplyImpl, multiplyComplexImpl);\n\nexport const multiplyConfig: KernelConfig = {\n kernelName: Multiply,\n backendName: 'cpu',\n kernelFunc: multiply\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, KernelConfig, KernelFunc, Neg, TensorInfo, TypedArray, UnaryInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {multiplyImpl} from './Multiply';\n\nexport function negImpl(xVals: TypedArray, xShape: number[], xDtype: DataType):\n [TypedArray, number[]] {\n const minusOne =\n util.createScalarValue(-1 as unknown as 'float32', xDtype) as TypedArray;\n return multiplyImpl([], xShape, minusOne, xVals, xDtype);\n}\n\nexport function neg(args: {inputs: UnaryInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n assertNotComplex(x, 'neg');\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const [res, newShape] = negImpl(xVals, x.shape, x.dtype);\n\n return backend.makeTensorInfo(newShape, x.dtype, res);\n}\n\nexport const negConfig: KernelConfig = {\n kernelName: Neg,\n backendName: 'cpu',\n kernelFunc: neg as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, NotEqual} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const notEqualImpl =\n createSimpleBinaryKernelImpl(((a, b) => (a !== b) ? 1 : 0));\nexport const notEqual =\n binaryKernelFunc(NotEqual, notEqualImpl, null /* complexOp */, 'bool');\n\nexport const notEqualConfig: KernelConfig = {\n kernelName: NotEqual,\n backendName: 'cpu',\n kernelFunc: notEqual\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, NumericDataType, TypedArray} from '@tensorflow/tfjs-core';\nimport {util} from '@tensorflow/tfjs-core';\n\nexport function transposeImpl(\n xVals: TypedArray, xShape: number[], dtype: DataType, perm: number[],\n newShape: number[]): TypedArray {\n const xRank = xShape.length;\n const xSize = util.sizeFromShape(xShape);\n const xStrides = util.computeStrides(xShape);\n const newStrides = util.computeStrides(newShape);\n\n const result = util.getTypedArrayFromDType(\n dtype as NumericDataType, util.sizeFromShape(newShape));\n\n for (let i = 0; i < xSize; ++i) {\n const loc = util.indexToLoc(i, xRank, xStrides);\n\n // Permute location.\n const newLoc: number[] = new Array(loc.length);\n for (let i = 0; i < newLoc.length; i++) {\n newLoc[i] = loc[perm[i]];\n }\n\n const newIndex = util.locToIndex(newLoc, xRank, newStrides);\n result[newIndex] = xVals[i];\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Transpose, TransposeAttrs, TransposeInputs, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {transposeImpl} from './Transpose_impl';\n\nexport function transpose(args: {\n inputs: TransposeInputs,\n attrs: TransposeAttrs,\n backend: MathBackendCPU\n}): TensorInfo {\n const {inputs, attrs, backend} = args;\n const {x} = inputs;\n const {perm} = attrs;\n\n assertNotComplex(x, 'transpose');\n\n const xRank = x.shape.length;\n\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[perm[i]];\n }\n\n const values = backend.data.get(x.dataId).values as TypedArray;\n const result = transposeImpl(values, x.shape, x.dtype, perm, newShape);\n\n const dataId = backend.write(result, newShape, x.dtype);\n return {dataId, shape: newShape, dtype: x.dtype};\n}\n\nexport const transposeConfig: KernelConfig = {\n kernelName: Transpose,\n backendName: 'cpu',\n kernelFunc: transpose as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, KernelConfig, KernelFunc, Prod, ProdAttrs, ProdInputs, TensorInfo, TypedArray, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function prodImpl(\n xShape: number[], xDtype: DataType, xVals: TypedArray,\n reductionAxes: number[]):\n {outVals: TypedArray, outShape: number[], outDtype: DataType} {\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(xShape, reductionAxes);\n const outDtype = upcastType(xDtype, 'int32');\n const outVals = util.makeZerosTypedArray(\n util.sizeFromShape(outShape), outDtype) as TypedArray;\n const reduceSize = util.sizeFromShape(reduceShape);\n\n for (let i = 0; i < outVals.length; ++i) {\n const offset = i * reduceSize;\n let prod = 1;\n for (let j = 0; j < reduceSize; ++j) {\n prod *= xVals[offset + j];\n }\n outVals[i] = prod;\n }\n\n return {outVals, outShape, outDtype};\n}\n\nexport function prod(\n args: {inputs: ProdInputs, backend: MathBackendCPU, attrs: ProdAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'prod');\n\n const xRank = x.shape.length;\n const axes = util.parseAxisParam(axis, x.shape);\n\n const permutation = backend_util.getAxesPermutation(axes, xRank);\n let reductionAxes = axes;\n let permutedX = x;\n const intermediateTensorInfos = [];\n if (permutation != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n intermediateTensorInfos.push(permutedX);\n reductionAxes = backend_util.getInnerMostAxes(reductionAxes.length, xRank);\n }\n\n const xVals = backend.data.get(permutedX.dataId).values as TypedArray;\n const {outVals, outShape, outDtype} =\n prodImpl(permutedX.shape, permutedX.dtype, xVals, reductionAxes);\n\n let resultShape = outShape;\n if (keepDims) {\n resultShape = backend_util.expandShapeToKeepDim(outShape, axes);\n }\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(resultShape, outDtype, outVals);\n}\n\nexport const prodConfig: KernelConfig = {\n kernelName: Prod,\n backendName: 'cpu',\n kernelFunc: prod as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nfunction validateIndices(\n indices: TypedArray, indicesShape: number[], numParams: number) {\n indices.forEach((index: number, i: number) => {\n if (index < 0 || index >= numParams) {\n const locString =\n util.indexToLoc(\n i, indicesShape.length, util.computeStrides(indicesShape))\n .join(',');\n throw new Error(\n `indices[${locString}] = ${index} is not in [0, ${numParams})`);\n }\n });\n}\n\nfunction validateSplits(\n paramsNestedSplits: TypedArray[], numParamsDenseValues: number) {\n // Validate\n for (let dim = 0; dim < paramsNestedSplits.length; ++dim) {\n const splits = paramsNestedSplits[dim];\n const lastSplit = (dim === paramsNestedSplits.length - 1) ?\n numParamsDenseValues :\n paramsNestedSplits[dim + 1].length;\n if (splits.length === 0) {\n throw new Error('Ragged splits may not be empty');\n }\n if (splits[0] < 0) {\n throw new Error('Ragged splits must be non-negative');\n }\n if (splits[splits.length - 1] > lastSplit) {\n throw new Error('Ragged splits must not point past values');\n }\n for (let i = 1; i < splits.length; ++i) {\n if (splits[i - 1] > splits[i]) {\n throw new Error('Ragged splits must be sorted in ascending order');\n }\n }\n }\n}\n\n// Construct the `splits` output tensors, encoded using a nested vector.\n// Also find the slices of values that need to be copied, and store them\n// in `valueSlices`. The total number of values that will be copied (which\n// we need for allocating the output values tensor) is stored in `numValues`.\nfunction makeSplits(\n indices: TypedArray, indicesShape: number[],\n paramsNestedSplits: TypedArray[], numParamsDenseValues: number) {\n const valueSlices: Array<[number, number]> = [];\n let numValues = 0;\n\n const numSplits = indicesShape.length - 1 + paramsNestedSplits.length;\n const outSplits = new Array(numSplits).fill(null).map(() => [0]);\n\n validateSplits(paramsNestedSplits, numParamsDenseValues);\n\n // Add `splits` that come from all but the last dimension of the dense\n // Tensor `indices`. In particular, for each dimension D, we add a\n // splits tensor whose values are:\n // range(reduceProd(splits.shape[:D]) + 1) * splits.shape[D+1]\n // E.g., if indices.shape=[2, 3, 4] then we will add splits tensors:\n // [0, 3, 6] # length=2+1, stride=3\n // [0, 4, 8, 12, 16, 20, 24] # length=2*3+1, stride=4\n let nrows = 1;\n for (let dim = 0; dim < indicesShape.length - 1; ++dim) {\n nrows *= indicesShape[dim];\n const rowLength = indicesShape[dim + 1];\n for (let i = 1; i < nrows + 1; ++i) {\n outSplits[dim].push(i * rowLength);\n }\n }\n\n // Add `splits` that come from `paramsNestedSplits`. Starting with the\n // outermost ragged dimension (i.e., the first `splits` tensor), we work\n // our way in, finding the range of values that should be copied. As we\n // go, we update the output `splits` for each dimension with the appropriate\n // values. In particular, the *lengths* of the slices from `param_splits`\n // should be copied to generate corresponding slice lengths in the output\n // splits. E.g., if we are copying a ragged row with length 4, then we\n // should add a new split point to outSplits that is 4 greater than the\n // previous split point in outSplits.\n for (let i = 0; i < indices.length; ++i) {\n let start = indices[i];\n let limit = indices[i] + 1;\n\n // Copy splits.\n for (let dim = 0; dim < paramsNestedSplits.length; ++dim) {\n const splits = paramsNestedSplits[dim];\n const outDim = dim + indicesShape.length - 1;\n if (outDim >= 0) {\n const outSplitsOutDim = outSplits[outDim];\n const delta =\n outSplitsOutDim[outSplitsOutDim.length - 1] - splits[start];\n for (let j = start; j < limit; ++j) {\n outSplits[outDim].push(splits[j + 1] + delta);\n }\n }\n start = splits[start];\n limit = splits[limit];\n }\n if (limit !== start) {\n valueSlices.push([start, limit]);\n numValues += limit - start;\n }\n }\n\n return {outSplits, valueSlices, numValues};\n}\n\nfunction getSplits(outSplits: number[][]) {\n const splitsOut: TypedArray[] = [];\n for (let i = 0; i < outSplits.length; ++i) {\n const numSplits = outSplits[i].length;\n const splits = util.getArrayFromDType('int32', numSplits) as TypedArray;\n splitsOut.push(splits);\n\n outSplits[i].forEach((value, j: number) => splits[j] = value);\n }\n\n return splitsOut;\n}\n\nfunction computeFlatOuterDims(orig: number[], numOutDims: number) {\n const outDims = orig.slice(0, numOutDims);\n while (outDims.length < numOutDims) {\n outDims.push(1);\n }\n\n for (let inDim = numOutDims; inDim < orig.length; inDim++) {\n outDims[numOutDims - 1] *= orig[inDim];\n }\n\n return outDims;\n}\n// For each slice in `(start, limit)` in `valueSlices`, append\n// `paramsDenseValues[start,...,limit] to `values`. `valueSize` indicates\n// the number of scalars contained in each value paramsDenseValues[i].\nfunction writeValueSlices(\n paramsDenseValues: TypedArray, paramsDenseValuesShape: number[],\n valueSlices: Array<[number, number]>, valueSize: number, values: TypedArray,\n valuesShape: number[]) {\n const denseM = computeFlatOuterDims(paramsDenseValuesShape, 2)[1];\n const valuesM = computeFlatOuterDims(valuesShape, 2)[1];\n\n let outPos = 0;\n for (const slice of valueSlices) {\n for (let i = slice[0]; i < slice[1]; ++i) {\n for (let j = 0; j < valueSize; ++j) {\n values[outPos * valuesM + j] = paramsDenseValues[i * denseM + j];\n }\n ++outPos;\n }\n }\n}\n\nfunction getValues(\n paramsDenseValues: TypedArray, paramsDenseValuesShape: number[],\n paramsDenseValuesDType: DataType, valueSlices: Array<[number, number]>,\n numValues: number): [TypedArray, number[]] {\n const valuesShape = paramsDenseValuesShape.slice();\n valuesShape[0] = numValues;\n\n const valuesOut = util.getArrayFromDType(\n paramsDenseValuesDType,\n util.sizeFromShape(valuesShape)) as TypedArray;\n\n const numElements = paramsDenseValues.length;\n const valueSize =\n numElements === 0 ? 0 : (numElements / paramsDenseValuesShape[0]);\n writeValueSlices(\n paramsDenseValues, paramsDenseValuesShape, valueSlices, valueSize,\n valuesOut, valuesShape);\n\n return [valuesOut, valuesShape];\n}\nexport function raggedGatherImpl(\n paramsNestedSplits: TypedArray[], paramsNestedSplitsShapes: number[][],\n paramsDenseValues: TypedArray, paramsDenseValuesShape: number[],\n paramsDenseValuesDType: DataType, indices: TypedArray,\n indicesShape: number[],\n outputRaggedRank: number): [TypedArray[], TypedArray, number[]] {\n if (paramsNestedSplits.length === 0) {\n throw new Error('paramsNestedSplits must be non empty');\n }\n\n if (paramsNestedSplitsShapes[0].length === 0) {\n throw new Error('Split tensors must not be scalars');\n }\n const numParams = paramsNestedSplitsShapes[0][0] - 1;\n validateIndices(indices, indicesShape, numParams);\n\n if (paramsDenseValuesShape.length === 0) {\n throw new Error('params.rank must be nonzero');\n }\n const numParamsDenseValues = paramsDenseValuesShape[0];\n\n // Calculate the `splits`, and store the value slices that we need to\n // copy in `valueSlices`.\n const {outSplits, valueSlices, numValues} = makeSplits(\n indices, indicesShape, paramsNestedSplits, numParamsDenseValues);\n\n // Write the output tensors.\n const outputNestedSplits = getSplits(outSplits);\n const outputDenseValues = getValues(\n paramsDenseValues, paramsDenseValuesShape, paramsDenseValuesDType,\n valueSlices, numValues);\n\n return [outputNestedSplits, outputDenseValues[0], outputDenseValues[1]];\n}\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nconst INT32_MAX = 2147483647;\n\nexport function raggedRangeImpl(\n starts: TypedArray, startsShape: number[], startsDType: DataType,\n limits: TypedArray, limitsShape: number[], deltas: TypedArray,\n deltasShape: number[]): [TypedArray, TypedArray] {\n // Check input tensor shapes.\n if (startsShape.length > 1) {\n throw new Error('starts must be a scalar or vector');\n }\n if (limitsShape.length > 1) {\n throw new Error('limits must be a scalar or vector');\n }\n if (deltasShape.length > 1) {\n throw new Error('deltas must be a scalar or vector');\n }\n\n // Determine which tensors we need to broadcast.\n const broadcastStarts = startsShape.length === 0;\n const broadcastLimits = limitsShape.length === 0;\n const broadcastDeltas = deltasShape.length === 0;\n\n // nRows (number of output rows) is the size of the non-broadcast inputs,\n // or 1 if all inputs are scalars.\n const inSizes: number[] = [];\n if (!broadcastStarts) {\n inSizes.push(startsShape[0]);\n }\n if (!broadcastLimits) {\n inSizes.push(limitsShape[0]);\n }\n if (!broadcastDeltas) {\n inSizes.push(deltasShape[0]);\n }\n\n for (let i = 1; i < inSizes.length; ++i) {\n if (inSizes[i] !== inSizes[i - 1]) {\n throw new Error('starts, limits, and deltas must have the same shape');\n }\n }\n const nRows = inSizes.length === 0 ? 1 : inSizes[0];\n\n // Construct the rtNestedSplits tensor.\n const rtNestedSplits =\n util.getArrayFromDType('int32', nRows + 1) as TypedArray;\n rtNestedSplits[0] = 0;\n for (let row = 0; row < nRows; ++row) {\n const start = broadcastStarts ? starts[0] : starts[row];\n const limit = broadcastLimits ? limits[0] : limits[row];\n const delta = broadcastDeltas ? deltas[0] : deltas[row];\n if (delta === 0) {\n throw new Error('Requires delta != 0');\n }\n let size: number; // The number of elements in the specified range.\n if (((delta > 0) && (limit < start)) || ((delta < 0) && (limit > start))) {\n size = 0;\n } else {\n size = Math.ceil(Math.abs((limit - start) / delta));\n\n if (size > INT32_MAX) {\n throw new Error(`Requires ((limit - start) / delta) <= ${INT32_MAX}`);\n }\n }\n rtNestedSplits[row + 1] = rtNestedSplits[row] + size;\n }\n\n const nVals = rtNestedSplits[nRows];\n\n // Construct the rtDenseValues tensor.\n const rtDenseValues =\n util.getArrayFromDType(startsDType, nVals) as TypedArray;\n\n let valueIndex = 0;\n for (let row = 0; row < nRows; ++row) {\n const rowSize = rtNestedSplits[row + 1] - rtNestedSplits[row];\n let value = broadcastStarts ? starts[0] : starts[row];\n const delta = broadcastDeltas ? deltas[0] : deltas[row];\n for (let i = 0; i < rowSize; ++i) {\n rtDenseValues[valueIndex++] = value;\n value += delta;\n }\n }\n\n return [rtNestedSplits, rtDenseValues];\n}\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, broadcastTo, DataType, reshape, tidy, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport RowPartitionType = backend_util.RowPartitionType;\n// Based on\n// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc\nclass RaggedTensorToTensorOp {\n private readonly rowPartitionTypes: RowPartitionType[];\n private readonly raggedRank: number;\n constructor(\n private shape: TypedArray, private shapeShape: number[],\n private values: TypedArray, private valuesShape: number[],\n private valuesDType: DataType, private defaultValue: TypedArray,\n private defaultValueShape: number[],\n private readonly rowPartitionValues: TypedArray[],\n private readonly rowPartitionValuesShapes: number[][],\n rowPartitionTypeStrings: string[]) {\n this.rowPartitionTypes =\n backend_util.getRowPartitionTypesHelper(rowPartitionTypeStrings);\n this.raggedRank = backend_util.getRaggedRank(this.rowPartitionTypes);\n }\n\n private getRowPartitionTypeByDimension(dimension: number) {\n if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {\n return this.rowPartitionTypes[dimension + 1];\n } else {\n return this.rowPartitionTypes[dimension];\n }\n }\n\n // Returns the relationship between dimension and dimension + 1.\n private getRowPartitionTensor(dimension: number) {\n if (this.rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {\n return this.rowPartitionValues[dimension + 1];\n } else {\n return this.rowPartitionValues[dimension];\n }\n }\n\n private getMaxWidth(dimension: number) {\n const rowPartitionTensor = this.getRowPartitionTensor(dimension - 1);\n switch (this.getRowPartitionTypeByDimension(dimension - 1)) {\n case RowPartitionType.VALUE_ROWIDS:\n return RaggedTensorToTensorOp.getMaxWidthValueRowID(rowPartitionTensor);\n case RowPartitionType.ROW_SPLITS:\n return RaggedTensorToTensorOp.getMaxWidthRowSplit(rowPartitionTensor);\n default:\n throw new Error(`Cannot handle partition type ${\n RowPartitionType[this.getRowPartitionTypeByDimension(\n dimension - 1)]}`);\n }\n }\n\n static getMaxWidthRowSplit(rowSplit: TypedArray) {\n const tensorLength = rowSplit.length;\n if (tensorLength === 0 || tensorLength === 1) {\n return 0;\n }\n let maxWidth = 0;\n for (let i = 0; i < tensorLength - 1; ++i) {\n const currentWidth = rowSplit[i + 1] - rowSplit[i];\n if (currentWidth > maxWidth) {\n maxWidth = currentWidth;\n }\n }\n return maxWidth;\n }\n\n static getMaxWidthValueRowID(valueRowIds: TypedArray) {\n const indexLength = valueRowIds.length;\n if (indexLength === 0) {\n return 0;\n }\n let firstEqualIndex = 0;\n let firstEqualIndexValue = valueRowIds[0];\n let maxWidth = 0;\n for (let i = 1; i < indexLength; ++i) {\n const value = valueRowIds[i];\n if (value !== firstEqualIndexValue) {\n firstEqualIndexValue = value;\n maxWidth = Math.max(i - firstEqualIndex, maxWidth);\n firstEqualIndex = i;\n }\n }\n return Math.max(indexLength - firstEqualIndex, maxWidth);\n }\n\n private tensorShapeFromTensor(\n t: TypedArray, tShape: number[], isPartial = true) {\n if (tShape.length === 0) {\n if (t[0] === -1) {\n return [];\n }\n throw new Error(\n `The only valid scalar shape tensor is the fully unknown shape specified as -1.`);\n }\n // MakePartialShape/MakeShapeHelper.\n return makeShape(t, isPartial);\n }\n\n private calculateOutputSize(firstDim: number) {\n const valueShape = this.valuesShape;\n const defaultValueShape = this.defaultValueShape;\n\n backend_util.validateDefaultValueShape(defaultValueShape, valueShape);\n\n const shape = this.tensorShapeFromTensor(this.shape, this.shapeShape);\n const outputShape = backend_util.combineRaggedTensorToTensorShapes(\n this.raggedRank, shape, valueShape);\n\n const result = outputShape;\n\n if (result[0] < 0) {\n result[0] = firstDim;\n }\n for (let i = 1; i <= this.raggedRank; ++i) {\n if (result[i] < 0) {\n result[i] = this.getMaxWidth(i);\n }\n }\n\n return result;\n }\n\n /**\n * The outputIndex represents the index in the output tensor\n * where the first element of a particular dimension would be written.\n * If it is -1, it indicates that the index is out of scope.\n * Example, given firstDimension = 10, firstDimensionOutput = 6,\n * and outputIndexMultiplier = 100:\n * result = [0 100 200 300 400 500 -1 -1 -1 -1]\n * If firstDimensionOutput = 11 instead, then:\n * result = [0 100 200 300 400 500 600 700 800 900]\n */\n private calculateFirstParentOutputIndex(\n firstDimension: number, outputIndexMultiplier: number,\n firstDimensionOutput: number) {\n const minDimension = Math.min(firstDimension, firstDimensionOutput);\n const result: number[] = [];\n let currentOutputIndex = 0;\n for (let i = 0; i < minDimension;\n ++i, currentOutputIndex += outputIndexMultiplier) {\n result.push(currentOutputIndex);\n }\n for (let i = minDimension; i < firstDimension; ++i) {\n result.push(-1);\n }\n util.assert(\n result.length === firstDimension,\n () => 'Final length of result must be equal to firstDimension.');\n\n return result;\n }\n\n private calculateOutputIndexRowSplit(\n rowSplit: TypedArray, parentOutputIndex: number[],\n outputIndexMultiplier: number, outputSize: number) {\n const rowSplitSize = rowSplit.length;\n const result: number[] = [];\n for (let i = 0; i < rowSplitSize - 1; ++i) {\n const rowLength = rowSplit[i + 1] - rowSplit[i];\n let realLength = Math.min(outputSize, rowLength);\n let parentOutputIndexCurrent = parentOutputIndex[i];\n\n if (parentOutputIndexCurrent === -1) {\n realLength = 0;\n }\n for (let j = 0; j < realLength; ++j) {\n result.push(parentOutputIndexCurrent);\n parentOutputIndexCurrent += outputIndexMultiplier;\n }\n for (let j = 0; j < rowLength - realLength; ++j) {\n result.push(-1);\n }\n }\n if (rowSplitSize > 0 && result.length !== rowSplit[rowSplitSize - 1]) {\n throw new Error('Invalid row split size.');\n }\n\n return result;\n }\n\n // Calculate the output index of the first element of a list.\n // The parentOutputIndex is the same computation for the previous list.\n // -1 indicates an element or list that is out of range.\n // The outputIndexMultiplier is the number of output indices one moves\n // forward for each column.\n // E.g., given:\n // valueRowIds:[0 1 2 2 2 3 5 5 6]\n // parentOutputIndex:[1000 1100 2000 2100 -1 3000 4000]\n // outputIndexMultiplier: 10\n // outputSize: 2\n // You get:\n // result = [1000 1100 2000 2010 -1 2100 -1 -1 3000]\n // result[0] = parentOutputIndex[valueRowIds[0]]\n // result[1] = parentOutputIndex[valueRowIds[1]]\n // result[2] = parentOutputIndex[valueRowIds[2]]\n // result[3] = parentOutputIndex[valueRowIds[2] + 10]\n // result[4] = -1 because it is the third element the size is 2.\n // result[5] = parentOutputIndex[valueRowIds[3]]\n // result[6] = -1 because parentOutputIndex[valueRowIds[6]] == -1\n // result[7] = -1 because parentOutputIndex[valueRowIds[6]] == -1\n // result[8] = parentOutputIndex[valueRowIds[7]]\n private calculateOutputIndexValueRowID(\n valueRowIds: TypedArray, parentOutputIndex: number[],\n outputIndexMultiplier: number, outputSize: number) {\n const indexSize = valueRowIds.length;\n const result: number[] = [];\n if (indexSize === 0) {\n return [];\n }\n\n let currentOutputColumn = 0;\n let currentValueRowId = valueRowIds[0];\n\n if (currentValueRowId >= parentOutputIndex.length) {\n throw new Error(\n `Got currentValueRowId=${currentValueRowId}, which is not less than ${\n parentOutputIndex.length}`);\n }\n\n let currentOutputIndex = parentOutputIndex[currentValueRowId];\n result.push(currentOutputIndex);\n for (let i = 1; i < indexSize; ++i) {\n const nextValueRowId = valueRowIds[i];\n if (nextValueRowId === currentValueRowId) {\n if (currentOutputIndex >= 0) {\n ++currentOutputColumn;\n if (currentOutputColumn < outputSize) {\n currentOutputIndex += outputIndexMultiplier;\n } else {\n currentOutputIndex = -1;\n }\n }\n } else {\n currentOutputColumn = 0;\n currentValueRowId = nextValueRowId;\n\n if (nextValueRowId >= parentOutputIndex.length) {\n throw new Error(\n `Got nextValueRowId=${nextValueRowId} which is not less than ${\n parentOutputIndex.length}`);\n }\n\n currentOutputIndex = parentOutputIndex[nextValueRowId];\n }\n result.push(currentOutputIndex);\n }\n\n if (result.length !== valueRowIds.length) {\n throw new Error('Invalid row ids.');\n }\n\n return result;\n }\n\n private calculateOutputIndex(\n dimension: number, parentOutputIndex: number[],\n outputIndexMultiplier: number, outputSize: number) {\n const rowPartitionTensor = this.getRowPartitionTensor(dimension);\n const partitionType = this.getRowPartitionTypeByDimension(dimension);\n switch (partitionType) {\n case RowPartitionType.VALUE_ROWIDS:\n return this.calculateOutputIndexValueRowID(\n rowPartitionTensor, parentOutputIndex, outputIndexMultiplier,\n outputSize);\n case RowPartitionType.ROW_SPLITS:\n if (rowPartitionTensor.length - 1 > parentOutputIndex.length) {\n throw new Error(`Row partition size is greater than output size: ${\n rowPartitionTensor.length - 1} > ${parentOutputIndex.length}`);\n }\n return this.calculateOutputIndexRowSplit(\n rowPartitionTensor, parentOutputIndex, outputIndexMultiplier,\n outputSize);\n default:\n throw new Error(\n `Unsupported partition type: ${RowPartitionType[partitionType]}`);\n }\n }\n\n private getFirstDimensionSize() {\n const firstPartitionTensor = this.rowPartitionValues[0];\n if (this.rowPartitionTypes.length === 0) {\n throw new Error('No row_partition_types given.');\n }\n const firstPartitionType = this.rowPartitionTypes[0];\n switch (firstPartitionType) {\n case RowPartitionType.FIRST_DIM_SIZE:\n return firstPartitionTensor[0];\n case RowPartitionType.VALUE_ROWIDS:\n throw new Error('Cannot handle VALUE_ROWIDS in first dimension.');\n case RowPartitionType.ROW_SPLITS:\n return this.rowPartitionValuesShapes[0][0] - 1;\n default:\n throw new Error(\n `Cannot handle type ${RowPartitionType[firstPartitionType]}`);\n }\n }\n\n compute(): [number[], TypedArray] {\n const firstPartitionTensor = this.rowPartitionValues[0];\n if (firstPartitionTensor.length <= 0) {\n throw new Error(\n 'Invalid first partition input. ' +\n 'Tensor requires at least one element.');\n }\n const firstDimension = this.getFirstDimensionSize();\n const outputSize = this.calculateOutputSize(firstDimension);\n const multiplier: number[] = new Array(this.raggedRank + 1);\n\n multiplier[multiplier.length - 1] = 1;\n for (let i = multiplier.length - 2; i >= 0; --i) {\n multiplier[i] = multiplier[i + 1] * outputSize[i + 1];\n }\n // Full size of the tensor.\n const outputShape: number[] = makeShape(outputSize, false);\n const outputTensor =\n util.getArrayFromDType(\n this.valuesDType, util.sizeFromShape(outputShape)) as TypedArray;\n\n const fullSize = multiplier[0] * outputSize[0];\n if (fullSize > 0) {\n let outputIndex = this.calculateFirstParentOutputIndex(\n firstDimension, multiplier[0], outputSize[0]);\n for (let i = 1; i <= this.raggedRank; ++i) {\n const newOutputIndex = this.calculateOutputIndex(\n i - 1, outputIndex, multiplier[i], outputSize[i]);\n outputIndex = newOutputIndex;\n }\n\n this.setOutput(this.raggedRank, outputIndex, outputTensor, outputShape);\n }\n\n return [outputShape, outputTensor];\n }\n setOutput(\n raggedRank: number, outputIndex: number[], outputTensor: TypedArray,\n outputShape: number[]) {\n if (outputTensor.length === 0) {\n return;\n }\n\n const valuesBase = this.values;\n const outputBase = outputTensor;\n\n let elementShape = outputShape.slice();\n elementShape = elementShape.slice(raggedRank + 1);\n const valueElementSize = util.sizeFromShape(elementShape);\n const outputIndexSize = outputIndex.length;\n\n // Broadcast the default value to value_element_size. (We can skip this\n // if defaultValueTensor.size == 1, since we use fill when that's true.)\n let defaultValue = this.defaultValue;\n if (defaultValue.length !== valueElementSize && defaultValue.length !== 1) {\n const srcShape = this.defaultValueShape;\n tidy(() => {\n const defaultValueTensor = reshape(defaultValue, srcShape);\n const bCastDefault = broadcastTo(defaultValueTensor, elementShape);\n defaultValue = bCastDefault.dataSync();\n });\n }\n\n // Loop through the outputIndex array, finding contiguous regions that\n // should be copied. Once we find the end of a contiguous region, copy it\n // and add any necessary padding (with defaultValue).\n let srcStart = 0; // Start of contiguous region (in values)\n let dstStart = 0; // Destination for contiguous region (in output)\n let dstEnd = 0; // Destination for contiguous region (in output)\n for (let srcI = 0; srcI <= outputIndexSize; ++srcI) {\n // dstI is the destination where the value at srcI should be copied.\n let dstI = srcI < outputIndexSize ? outputIndex[srcI] : -1;\n\n // If we're still in a contiguous region, then update dstEnd go to the\n // next srcI.\n if (dstI === dstEnd) {\n ++dstEnd;\n continue;\n }\n\n // We found the end of contiguous region. This can be because we found\n // a gap (dstI > dstEnd), or a source value that shouldn't be copied\n // because it's out-of-bounds (dstI == -1), or the end of the tensor\n // (dstI === -1).\n if (dstStart < dstEnd) {\n // Copy the contiguous region.\n const src = valuesBase.subarray(srcStart * valueElementSize);\n const dst = outputBase.subarray(dstStart * valueElementSize);\n const nVals = (dstEnd - dstStart) * valueElementSize;\n copyArray(dst, src, nVals);\n }\n\n // Add any necessary padding (w/ defaultValue).\n if (srcI >= outputIndexSize) {\n // We reached the end of values: pad to the end of output.\n const outputSize = outputTensor.length;\n dstI = Math.floor(outputSize / valueElementSize);\n }\n if (dstI > dstEnd) {\n if (this.defaultValue.length === 1) {\n outputBase\n .subarray(dstEnd * valueElementSize, dstI * valueElementSize)\n .fill(this.defaultValue[0]);\n dstEnd = dstI;\n } else {\n while (dstI > dstEnd) {\n const dst = outputBase.slice(dstEnd * valueElementSize);\n copyArray(dst, defaultValue, valueElementSize);\n ++dstEnd;\n }\n }\n }\n\n // Update indices.\n if (dstI < 0) {\n // srcI should be skipped -- leave it out of the contiguous region.\n srcStart = srcI + 1;\n dstStart = dstEnd;\n } else {\n // srcI should be copied -- include it in the contiguous region.\n srcStart = srcI;\n dstStart = dstEnd;\n dstEnd = dstStart + 1;\n }\n }\n }\n}\n\nfunction copyArray(dst: TypedArray, src: TypedArray, size: number) {\n for (let i = 0; i < size; i++) {\n dst[i] = src[i];\n }\n}\n\nfunction makeShape(shape: number[]|TypedArray, isPartial: boolean) {\n const out: number[] = [];\n for (let dim of shape) {\n if (dim < 0) {\n if (!isPartial) {\n throw new Error(`Dimension ${dim} must be >= 0`);\n }\n if (dim < -1) {\n throw new Error(`Dimension ${dim} must be >= -1`);\n }\n dim = -1;\n }\n out.push(dim);\n }\n\n return out;\n}\n\nexport function raggedTensorToTensorImpl(\n shape: TypedArray, shapesShape: number[], values: TypedArray,\n valuesShape: number[], valuesDType: DataType, defaultValue: TypedArray,\n defaultValueShape: number[], rowPartitionValues: TypedArray[],\n rowPartitionValuesShapes: number[][],\n rowPartitionTypes: string[]): [number[], TypedArray] {\n return new RaggedTensorToTensorOp(\n shape, shapesShape, values, valuesShape, valuesDType, defaultValue,\n defaultValueShape, rowPartitionValues, rowPartitionValuesShapes,\n rowPartitionTypes)\n .compute();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataTypeMap, util} from '@tensorflow/tfjs-core';\n\nexport function rangeImpl(\n start: number, stop: number, step: number,\n dtype: 'float32'|'int32'): DataTypeMap['float32' | 'int32'] {\n const sameStartStop = start === stop;\n const increasingRangeNegativeStep = start < stop && step < 0;\n const decreasingRangePositiveStep = stop < start && step > 1;\n\n if (sameStartStop || increasingRangeNegativeStep ||\n decreasingRangePositiveStep) {\n return util.makeZerosTypedArray(0, dtype);\n }\n\n const numElements = Math.abs(Math.ceil((stop - start) / step));\n const values = util.makeZerosTypedArray(numElements, dtype);\n\n if (stop < start && step === 1) {\n // Auto adjust the step's sign if it hasn't been set\n // (or was set to 1)\n step = -1;\n }\n\n values[0] = start;\n for (let i = 1; i < values.length; i++) {\n values[i] = values[i - 1] + step;\n }\n return values;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Rsqrt} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const rsqrtImpl = createSimpleUnaryImpl((xi) => 1 / Math.sqrt(xi));\nexport const rsqrt = unaryKernelFuncFromImpl(Rsqrt, rsqrtImpl);\n\nexport const rsqrtConfig: KernelConfig = {\n kernelName: Rsqrt,\n backendName: 'cpu',\n kernelFunc: rsqrt,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {buffer, Rank, ShapeMap, TensorBuffer, TypedArray} from '@tensorflow/tfjs-core';\n\ninterface DefaultValueTypeMap {\n bool: boolean;\n int32: number;\n float32: number;\n string: string;\n}\n\nexport function\nscatterImpl(\n indices: TensorBuffer, updates: TensorBuffer,\n shape: number[], outputSize: number, sliceSize: number, numUpdates: number,\n sliceRank: number, strides: number[],\n defaultValue: TensorBuffer|DefaultValueTypeMap[D],\n sumDupeIndices: boolean): TensorBuffer {\n const flattenShape = [outputSize / sliceSize, sliceSize];\n\n const indicesData = indices.values as TypedArray;\n const updatesData = updates.values;\n\n if (outputSize === 0) {\n return buffer(shape as ShapeMap[R], updates.dtype);\n }\n\n const outBuf = (defaultValue instanceof TensorBuffer) ?\n defaultValue :\n buffer(flattenShape, updates.dtype);\n if (typeof defaultValue === 'string') {\n (outBuf.values as string[]).fill(defaultValue);\n } else if (typeof defaultValue === 'number') {\n (outBuf.values as TypedArray).fill(defaultValue);\n } else if (typeof defaultValue === 'boolean') {\n (outBuf.values as TypedArray).fill(+defaultValue);\n }\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 as TypedArray)[flattenIndex * sliceSize + k] +=\n (updatesData as TypedArray)[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;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sigmoid} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sigmoidImpl =\n createSimpleUnaryImpl((xi) => 1 / (1 + Math.exp(-xi)));\nexport const sigmoid =\n unaryKernelFunc(Sigmoid, (xi) => 1 / (1 + Math.exp(-xi)));\n\nexport const sigmoidConfig: KernelConfig = {\n kernelName: Sigmoid,\n backendName: 'cpu',\n kernelFunc: sigmoid,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BackendValues, buffer, DataType, KernelConfig, KernelFunc, Slice, slice_util, SliceAttrs, SliceInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function sliceImpl(\n vals: BackendValues, begin: number[], size: number[], shape: number[],\n dtype: DataType): BackendValues {\n const isContinous = slice_util.isSliceContinous(shape, begin, size);\n const length = util.sizeFromShape(size);\n const xStrides = util.computeStrides(shape);\n\n if (isContinous) {\n const flatOffset = slice_util.computeFlatOffset(begin, xStrides);\n\n if (dtype === 'string') {\n return (vals as Uint8Array[]).slice(flatOffset, flatOffset + length);\n }\n\n return (vals as TypedArray).subarray(flatOffset, flatOffset + length);\n }\n\n const decodedData = dtype === 'string' ?\n backend_util.fromUint8ToStringArray(vals as Uint8Array[]) :\n vals as TypedArray;\n\n const inBuf = buffer(shape, dtype, decodedData);\n const outBuf = buffer(size, dtype);\n for (let i = 0; i < outBuf.size; ++i) {\n const outLoc = outBuf.indexToLoc(i);\n const inLoc = outLoc.map((idx: number, j) => idx + begin[j]);\n outBuf.set(inBuf.get(...inLoc), ...outLoc);\n }\n\n if (dtype === 'string') {\n return backend_util.fromStringArrayToUint8(outBuf.values as string[]);\n }\n return outBuf.values as TypedArray;\n}\n\nexport function slice(\n args: {inputs: SliceInputs, backend: MathBackendCPU, attrs: SliceAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {begin, size} = attrs;\n\n assertNotComplex(x, 'slice');\n\n const [$begin, $size] = slice_util.parseSliceParams(x, begin, size);\n slice_util.assertParamsValid(x, $begin, $size);\n\n const vals = backend.data.get(x.dataId).values;\n const outVals = sliceImpl(vals, $begin, $size, x.shape, x.dtype);\n return backend.makeTensorInfo($size, x.dtype, outVals);\n}\n\nexport const sliceConfig: KernelConfig = {\n kernelName: Slice,\n backendName: 'cpu',\n kernelFunc: slice as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 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, 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(\n backend_util.getSparseFillEmptyRowsIndicesDenseShapeMismatch(\n 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(\n backend_util.getSparseFillEmptyRowsNegativeIndexErrorMessage(i, row));\n }\n if (row >= denseRows) {\n throw new Error(\n backend_util.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(\n i, 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 {backend_util, 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(\n backend_util\n .getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(\n unknownIndex, d));\n }\n unknownIndex = d;\n outputShape.push(1);\n } else {\n if (size < 0) {\n throw new Error(\n backend_util.getSparseReshapeNegativeOutputDimErrorMessage(\n d, size));\n }\n product *= size;\n outputShape.push(size);\n }\n }\n if (unknownIndex !== -1) {\n if (product <= 0) {\n throw new Error(\n backend_util.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());\n }\n const missing = Math.trunc(denseSize / product);\n if (product * missing !== denseSize) {\n throw new Error(\n backend_util.getSparseReshapeInputOutputMultipleErrorMessage(\n inputShape, outputShape));\n }\n\n outputShape[unknownIndex] = missing;\n }\n const outputSize = util.sizeFromShape(outputShape);\n if (outputSize !== denseSize) {\n throw new Error(\n backend_util.getSparseReshapeInputOutputMismatchErrorMessage(\n inputShape, 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 {backend_util, 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\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(\n backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());\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(\n backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());\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(backend_util\n .getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage());\n }\n }\n\n if (outIndex < 0 || outIndex >= outputRows) {\n throw new Error(\n backend_util.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(\n outIndex, outputRows));\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(\n backend_util.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(\n i, indices[i], inputFlat[0]));\n }\n for (let j = 0; j < numCol; j++) {\n output[outIndex * numCol + j] += input[index * numCol + j];\n }\n }\n\n if (isMean) {\n for (let j = 0; j < numCol; j++) {\n output[outIndex * numCol + j] /= end - start;\n }\n }\n\n start = end;\n ++end;\n uninitializedIndex = outIndex + 1;\n outIndex = nextIndex;\n if (end > numIndices) {\n break;\n }\n }\n\n // Fill the gap at the end with the default value.\n if (uninitializedIndex < outputRows) {\n output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);\n }\n\n return [output, outputShape];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sqrt} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sqrtImpl = createSimpleUnaryImpl((xi) => Math.sqrt(xi));\nexport const sqrt = unaryKernelFunc(Sqrt, (xi) => Math.sqrt(xi));\n\nexport const sqrtConfig: KernelConfig = {\n kernelName: Sqrt,\n backendName: 'cpu',\n kernelFunc: sqrt,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SquaredDifference} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const squaredDifferenceImpl =\n createSimpleBinaryKernelImpl(((a: number, b: number) => {\n const diff = a - b;\n return diff * diff;\n }));\nexport const squaredDifference =\n binaryKernelFunc(SquaredDifference, squaredDifferenceImpl);\n\nexport const squaredDifferenceConfig: KernelConfig = {\n kernelName: SquaredDifference,\n backendName: 'cpu',\n kernelFunc: squaredDifference\n};\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, StaticRegexReplace, StaticRegexReplaceAttrs} from '@tensorflow/tfjs-core';\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const staticRegexReplaceImpl = createSimpleUnaryImpl((x: string, attrs) => {\n const {pattern, replaceGlobal, rewrite} =\n attrs as unknown as StaticRegexReplaceAttrs;\n // TODO(mattSoulanille): Don't create a regex each time.\n return x.replace(new RegExp(pattern, replaceGlobal ? 'g' : ''), rewrite);\n});\n\nconst staticRegexReplace =\n unaryKernelFuncFromImpl(StaticRegexReplace, staticRegexReplaceImpl);\n\nexport const staticRegexReplaceConfig: KernelConfig = {\n kernelName: StaticRegexReplace,\n backendName: 'cpu',\n kernelFunc: staticRegexReplace,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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(\n outShape: number[], xBuf: TensorBuffer, strides: number[],\n begin: number[]): TensorBuffer {\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;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {util} from '@tensorflow/tfjs-core';\n\n/**\n * The StringNGramsOp class creates ngrams from ragged string data.\n * The constructor contains all attributes related to the operation such as\n * padding widths and strings, and the compute function can be used to\n * compute the ngrams for different ragged tensor inputs.\n */\nclass StringNGramsOp {\n private separator: Uint8Array;\n private nGramWidths: number[];\n private padWidth: number;\n private leftPad: Uint8Array;\n private rightPad: Uint8Array;\n private preserveShort: boolean;\n\n constructor(\n separator: string, nGramWidths: number[], leftPad: string,\n rightPad: string, padWidth: number, preserveShortSequences: boolean) {\n this.separator = util.encodeString(separator);\n this.nGramWidths = nGramWidths;\n this.leftPad = util.encodeString(leftPad);\n this.rightPad = util.encodeString(rightPad);\n this.padWidth = padWidth;\n this.preserveShort = preserveShortSequences;\n }\n\n private getPadWidth(nGramWidth: number) {\n // Ngrams can be padded with either a fixed pad width or a dynamic pad\n // width depending on the 'padWidth' arg, but in no case should the padding\n // ever be wider than 'nGramWidth' - 1.\n return Math.min(\n this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);\n }\n\n private getNumNGrams(length: number, nGramWidth: number) {\n const padWidth = this.getPadWidth(nGramWidth);\n return Math.max(0, ((length + 2 * padWidth) - nGramWidth) + 1);\n }\n\n private createNGrams(\n data: Uint8Array[], splitIndex: number, output: Uint8Array[],\n outputStartIndex: number, numNGrams: number, nGramWidth: number) {\n for (let nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex) {\n const padWidth = this.getPadWidth(nGramWidth);\n const leftPadding = Math.max(0, padWidth - nGramIndex);\n const rightPadding =\n Math.max(0, padWidth - (numNGrams - (nGramIndex + 1)));\n const numTokens = nGramWidth - (leftPadding + rightPadding);\n const dataStartIndex =\n splitIndex + (leftPadding > 0 ? 0 : nGramIndex - padWidth);\n\n // Calculate the total expected size of the nGram so we can reserve the\n // correct amount of space in the string.\n let nGramSize = 0;\n // Size of the left padding.\n nGramSize += leftPadding * this.leftPad.length;\n // Size of the tokens.\n for (let n = 0; n < numTokens; ++n) {\n nGramSize += data[dataStartIndex + n].length;\n }\n // Size of the right padding.\n nGramSize += rightPadding * this.rightPad.length;\n // Size of the separators.\n const numSeparators = leftPadding + rightPadding + numTokens - 1;\n nGramSize += numSeparators * this.separator.length;\n\n // Build the nGram.\n output[outputStartIndex + nGramIndex] = new Uint8Array(nGramSize);\n const nGram = output[outputStartIndex + nGramIndex];\n\n let nextNGramIndex = 0;\n const appendToNGram = (str: Uint8Array) =>\n str.forEach((value) => nGram[nextNGramIndex++] = value);\n\n for (let n = 0; n < leftPadding; ++n) {\n appendToNGram(this.leftPad);\n appendToNGram(this.separator);\n }\n // Only output first numTokens - 1 pairs of data and separator\n for (let n = 0; n < numTokens - 1; ++n) {\n appendToNGram(data[dataStartIndex + n]);\n appendToNGram(this.separator);\n }\n // Handle case when there are no tokens or no right padding as these\n // can result in consecutive separators.\n if (numTokens > 0) {\n // If we have tokens, then output last and then pair each separator\n // with the right padding that follows, to ensure nGram ends either with\n // the token or with the right pad.\n appendToNGram(data[dataStartIndex + numTokens - 1]);\n for (let n = 0; n < rightPadding; ++n) {\n appendToNGram(this.separator);\n appendToNGram(this.rightPad);\n }\n } else {\n // If we don't have tokens, then the last item inserted into the nGram\n // has been the separator from the left padding loop above. Hence,\n // output right pad and separator and make sure to finish with a\n // padding, not a separator.\n for (let n = 0; n < rightPadding - 1; ++n) {\n appendToNGram(this.rightPad);\n appendToNGram(this.separator);\n }\n appendToNGram(this.rightPad);\n }\n }\n }\n\n // Data and splits together form the definition of the ragged tensor,\n // where data is 1 dimensional and contains the values of the tensor\n // and splits denotes the indices at which each row starts.\n public compute(data: Uint8Array[], splits: Int32Array):\n [Uint8Array[], Int32Array] {\n // Validate that the splits are valid indices into data, only if there are\n // splits specified.\n const inputDataSize = data.length;\n const splitsSize = splits.length;\n if (splitsSize > 0) {\n let prevSplit = splits[0];\n if (prevSplit !== 0) {\n throw new Error(`First split value must be 0, got ${prevSplit}`);\n }\n for (let i = 1; i < splitsSize; ++i) {\n let validSplits = splits[i] >= prevSplit;\n validSplits = validSplits && (splits[i] <= inputDataSize);\n if (!validSplits) {\n throw new Error(`Invalid split value ${splits[i]}, must be in [${\n prevSplit}, ${inputDataSize}]`);\n }\n prevSplit = splits[i];\n }\n if (prevSplit !== inputDataSize) {\n throw new Error(`Last split value must be data size. Expected ${\n inputDataSize}, got ${prevSplit}`);\n }\n }\n\n const numBatchItems = splitsSize - 1;\n const nGramsSplits = util.getArrayFromDType('int32', splitsSize);\n // If there is no data or size, return an empty ragged tensor.\n if (inputDataSize === 0 || splitsSize === 0) {\n const empty: Uint8Array[] = new Array(inputDataSize);\n for (let i = 0; i <= numBatchItems; ++i) {\n nGramsSplits[i] = 0;\n }\n return [empty, nGramsSplits];\n }\n\n nGramsSplits[0] = 0;\n for (let i = 1; i <= numBatchItems; ++i) {\n const length = splits[i] - splits[i - 1];\n let numNGrams = 0;\n this.nGramWidths.forEach((nGramWidth) => {\n numNGrams += this.getNumNGrams(length, nGramWidth);\n });\n if (this.preserveShort && length > 0 && numNGrams === 0) {\n numNGrams = 1;\n }\n nGramsSplits[i] = nGramsSplits[i - 1] + numNGrams;\n }\n\n const nGrams: Uint8Array[] = new Array(nGramsSplits[numBatchItems]);\n\n for (let i = 0; i < numBatchItems; ++i) {\n const splitIndex = splits[i];\n let outputStartIdx = nGramsSplits[i];\n this.nGramWidths.forEach((nGramWidth) => {\n const length = splits[i + 1] - splits[i];\n const numNGrams = this.getNumNGrams(length, nGramWidth);\n this.createNGrams(\n data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);\n outputStartIdx += numNGrams;\n });\n // If we're preserving short sequences, check to see if no sequence was\n // generated by comparing the current output start idx to the original\n // one (nGramSplitsdata). If no ngrams were generated, then they will\n // be equal (since we increment outputStartIdx by numNGrams every\n // time we create a set of ngrams.)\n if (this.preserveShort && outputStartIdx === nGramsSplits[i]) {\n const dataLength = splits[i + 1] - splits[i];\n // One legitimate reason to not have any ngrams when this.preserveShort\n // is true is if the sequence itself is empty. In that case, move on.\n if (dataLength === 0) {\n continue;\n }\n // We don't have to worry about dynamic padding sizes here: if padding\n // was dynamic, every sequence would have had sufficient padding to\n // generate at least one nGram.\n const nGramWidth = dataLength + 2 * this.padWidth;\n const numNGrams = 1;\n this.createNGrams(\n data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);\n }\n }\n return [nGrams, nGramsSplits];\n }\n}\n\nexport function stringNGramsImpl(\n data: Uint8Array[], dataSplits: Int32Array, separator: string,\n nGramWidths: number[], leftPad: string, rightPad: string, padWidth: number,\n preserveShortSequences: boolean): [Uint8Array[], Int32Array] {\n return new StringNGramsOp(\n separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences)\n .compute(data, dataSplits);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray, util} from '@tensorflow/tfjs-core';\n\nfunction split(\n str: Uint8Array, delimiters: Uint8Array, skipEmpty: boolean,\n result: Uint8Array[]): void {\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 for (let i = 0; i < str.length; ++i) {\n result.push(str.subarray(i, i + 1));\n }\n return;\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 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;\n }\n // When there are multiple delimiters, the input is split at every instance\n // one of the delimiters appears.\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}\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 prevTokensLength = tokens.length;\n split(input[i], delimiter, skipEmpty, tokens);\n const nEntries = tokens.length - prevTokensLength;\n numIndices[i] = nEntries;\n outputSize += nEntries;\n maxNumEntries = Math.max(maxNumEntries, nEntries);\n }\n\n const indices = util.getArrayFromDType('int32', outputSize * 2) as TypedArray;\n const values: Uint8Array[] = new Array(outputSize);\n const shape: [number, number] = [batchSize, maxNumEntries];\n\n let c = 0;\n for (let i = 0; i < batchSize; ++i) {\n for (let j = 0; j < numIndices[i]; ++j) {\n // indices is a 2d tensor with shape of [outputSize, 2]\n indices[c * 2] = i;\n indices[c * 2 + 1] = j;\n values[c] = tokens[c];\n ++c;\n }\n }\n\n return [indices, values, shape];\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function stringToHashBucketFastImpl(\n input: Uint8Array[], numBuckets: number): TypedArray {\n const output = util.getArrayFromDType('int32', input.length) as TypedArray;\n\n for (let i = 0; i < input.length; ++i) {\n output[i] =\n util.fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();\n }\n\n return output;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sub} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc, createComplexBinaryKernelImpl} from '../utils/binary_utils';\n\nexport const subImpl = createSimpleBinaryKernelImpl(\n ((aValue: number, bValue: number) => aValue - bValue));\nexport const subComplexImpl =\n createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n return {real: aReal - bReal, imag: aImag - bImag};\n }));\nexport const sub = binaryKernelFunc(Sub, subImpl, subComplexImpl);\n\nexport const subConfig: KernelConfig = {\n kernelName: Sub,\n backendName: 'cpu',\n kernelFunc: sub\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, DataType, Rank, TensorBuffer} from '@tensorflow/tfjs-core';\n\n/**\n * An implementation of the tile kernel shared between webgl and cpu for string\n * tensors only.\n */\n\nexport function tileImpl(\n xBuf: TensorBuffer,\n reps: number[]): TensorBuffer {\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;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n x: TypedArray, xShape: number[], xDtype: NumericDataType, k: number,\n sorted: boolean):\n [TensorBuffer, TensorBuffer] {\n // Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.\n const lastDim = xShape[xShape.length - 1];\n const [batch, size] = [x.length / lastDim, lastDim];\n const allTopKVals = util.getTypedArrayFromDType(xDtype, batch * k);\n const allTopKIndices = util.getTypedArrayFromDType('int32', batch * k);\n\n for (let b = 0; b < batch; b++) {\n const offset = b * size;\n const vals = x.subarray(offset, offset + size);\n\n let valAndInd: Pair[] = new Array(vals.length);\n vals.forEach(\n (value: number, index: number) => valAndInd[index] = {value, index});\n\n if (k < valAndInd.length) {\n select(valAndInd, k);\n valAndInd = valAndInd.slice(0, k);\n }\n\n if (sorted) {\n valAndInd.sort(comparePair);\n }\n \n const outOffset = b * k;\n const topKVals = allTopKVals.subarray(outOffset, outOffset + k);\n const topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);\n for (let i = 0; i < k; i++) {\n topKVals[i] = valAndInd[i].value;\n topKIndices[i] = valAndInd[i].index;\n }\n }\n // Reshape back to the original input shape, except that the last\n // dimension is k.\n const outputShape = xShape.slice();\n outputShape[outputShape.length - 1] = k;\n\n return [\n buffer(outputShape as ShapeMap[R], xDtype, allTopKVals),\n buffer(outputShape as ShapeMap[R], 'int32', allTopKIndices)\n ];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendValues, DataType, TensorBuffer, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function uniqueImpl(\n values: BackendValues, axis: number, shape: number[], dtype: DataType): {\n outputValues: BackendValues,\n outputShape: number[],\n indices: BackendValues\n} {\n // Normalize and validate axis.\n const $axis = util.parseAxisParam(axis, shape)[0];\n\n // Calculate the new shape that is suitable for extracting data along the\n // given axis.\n //\n // The rank is 3.\n // The size of the 1st dimension is the size of all the axes < the given axis.\n // The size of the 2nd dimension is the same as the size of the given axis.\n // The size of the 3rd dimension is the size of all the axes > the given axis.\n //\n // For example, for a 4D tensor with shape=[2, 3, 5, 4] and axis=2, the\n // newShape would be: [2*3, 5, 4].\n //\n // Note that this is not the final output shape. This will be the shape for an\n // intermediate TensorBuffer (see inputBuffer below) to allow us to extract\n // values along the given axis. To demonstrate how it works, consider the\n // following example:\n //\n // Input: a 3D tensor, with shape [1, 2, 3]\n // [\n // [\n // [1,2,3],\n // [4,5,6]\n // ]\n // ]\n // Axis: 2 (the last axis).\n // Along axis 2, we expect to extract 3 tensors: [1,4], [2,5], [3,6].\n //\n // For this example, newShape would be: [2, 3, 1], where 2 is calculated from\n // 1*2. The re-shaped data would look like:\n //\n // [\n // [\n // [1], [2], [3]\n // ],\n // [\n // [4], [5], [6]\n // ]\n // ]\n //\n // Then, we can construct a 3-level nested loop by the following dimension\n // order to extract the values along the axis (dimension1):\n // i: dimension1 // 0,1,2 (newShape[1])\n // m: dimension0 // 0,1 (newShape[0])\n // n: dimension2 // 0 (newShape[2])\n //\n // m, i, n\n // ---------\n // Iteration 0: data at [0, 0, 0] => \"1\"\n // Iteration 1: data at [1, 0, 0] => \"4\"\n // We got [1,4].\n // Iteration 2: data at [0, 1, 0] => \"2\"\n // Iteration 3: data at [1, 1, 0] => \"5\"\n // We got [2,5].\n // Iteration 4: data at [0, 2, 0] => \"3\"\n // Iteration 5: data at [1, 2, 0] => \"6\"\n // We got [3,6].\n const newShape = [1, shape[0], 1];\n for (let i = 0; i < $axis; i++) {\n newShape[0] *= shape[i];\n }\n newShape[1] = shape[$axis];\n for (let i = $axis + 1; i < shape.length; i++) {\n newShape[2] *= shape[i];\n }\n\n // A map from unique elements (their string representations) to their values\n // in \"indices\" (below).\n const uniqueElements = new Map();\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 const existingIndex = uniqueElements.get(element);\n if (existingIndex != null) {\n indices[i] = existingIndex;\n } else {\n const uniqueIndex = uniqueElements.size;\n uniqueElements.set(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] = uniqueElements.size;\n const outputBuffer = new TensorBuffer(outputTmpShape, dtype);\n uniqueIndices.forEach((uniqueElementIndex, i) => {\n for (let m = 0; m < newShape[0]; m++) {\n for (let n = 0; n < newShape[2]; n++) {\n outputBuffer.set(inputBuffer.get(m, uniqueElementIndex, n), m, i, n);\n }\n }\n });\n\n // The output shape can be calculated from the input shape with the size of\n // the given axis replaced by the number of unique elements along that axis.\n const outputShape = shape.slice();\n outputShape[$axis] = outputTmpShape[1];\n\n return {\n outputValues: outputBuffer.values as BackendValues,\n outputShape,\n indices,\n };\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.0';\nexport {version};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/*\n * base.ts contains all the exports from tfjs-backend-cpu\n * without auto-kernel registration\n */\nimport {registerBackend} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from './backend_cpu';\nimport * as shared from './shared';\n\nexport {MathBackendCPU} from './backend_cpu';\nexport {version as version_cpu} from './version';\nexport {shared};\n\n// Side effects for default initialization of MathBackendCPU\nregisterBackend('cpu', () => new MathBackendCPU(), 1 /* priority */);\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Elu, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const elu =\n unaryKernelFunc(Elu, (xi) => xi >= 0 ? xi : (Math.exp(xi) - 1));\n\nexport const eluConfig: KernelConfig = {\n kernelName: Elu,\n backendName: 'cpu',\n kernelFunc: elu,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LeakyRelu, LeakyReluAttrs, LeakyReluInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function leakyRelu(args: {\n inputs: LeakyReluInputs,\n backend: MathBackendCPU,\n attrs: LeakyReluAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {alpha} = attrs;\n\n assertNotComplex([x], 'leakyRelu');\n\n const xSize = util.sizeFromShape(x.shape);\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const outVals = util.getTypedArrayFromDType('float32', xSize);\n\n for (let i = 0; i < xVals.length; i++) {\n outVals[i] = xVals[i] < 0 ? alpha * xVals[i] : xVals[i];\n }\n\n return backend.makeTensorInfo(x.shape, 'float32', outVals);\n}\n\nexport const leakyReluConfig: KernelConfig = {\n kernelName: LeakyRelu,\n backendName: 'cpu',\n kernelFunc: leakyRelu as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Prelu, PreluInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\n\nconst preluImpl = createSimpleBinaryKernelImpl(\n (xValue: number, aValue: number) => xValue < 0 ? aValue * xValue : xValue);\n\nexport function prelu(args: {inputs: PreluInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x, alpha} = inputs;\n\n assertNotComplex([x, alpha], 'prelu');\n\n const aVals = backend.data.get(x.dataId).values as TypedArray;\n const bVals = backend.data.get(alpha.dataId).values as TypedArray;\n\n const [resultData, resultShape] =\n preluImpl(x.shape, alpha.shape, aVals, bVals, 'float32');\n\n return backend.makeTensorInfo(resultShape, 'float32', resultData);\n}\n\nexport const preluConfig: KernelConfig = {\n kernelName: Prelu,\n backendName: 'cpu',\n kernelFunc: prelu,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Relu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const relu = unaryKernelFunc(Relu, (xi) => Math.max(0, xi));\n\nexport const reluConfig: KernelConfig = {\n kernelName: Relu,\n backendName: 'cpu',\n kernelFunc: relu,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Relu6} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const relu6 =\n unaryKernelFunc(Relu6, (xi) => Math.min(Math.max(0, xi), 6));\n\nexport const relu6Config: KernelConfig = {\n kernelName: Relu6,\n backendName: 'cpu',\n kernelFunc: relu6,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, backend_util, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {elu} from '../kernels/Elu';\nimport {identity} from '../kernels/Identity';\nimport {leakyRelu} from '../kernels/LeakyRelu';\nimport {prelu} from '../kernels/Prelu';\nimport {relu} from '../kernels/Relu';\nimport {relu6} from '../kernels/Relu6';\nimport {sigmoid} from '../kernels/Sigmoid';\n\nexport function applyActivation(\n backend: MathBackendCPU, x: TensorInfo, activation: backend_util.Activation,\n preluActivationWeights?: TensorInfo, leakyreluAlpha?: number): TensorInfo {\n if (activation === 'linear') {\n return identity({inputs: {x}, backend});\n } else if (activation === 'relu') {\n return relu({inputs: {x}, backend}) as TensorInfo;\n } else if (activation === 'elu') {\n return elu({inputs: {x}, backend}) as TensorInfo;\n } else if (activation === 'relu6') {\n return relu6({inputs: {x}, backend}) as TensorInfo;\n } else if (activation === 'prelu') {\n return prelu({inputs: {x, alpha: preluActivationWeights}, backend});\n } else if (activation === 'leakyrelu') {\n return leakyRelu({inputs: {x}, backend, attrs: {alpha: leakyreluAlpha}});\n } else if (activation === 'sigmoid') {\n return sigmoid({inputs: {x}, backend}) as TensorInfo;\n }\n throw new Error(\n `Activation ${activation} has not been implemented for the CPU backend.`);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Reshape, ReshapeAttrs, ReshapeInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function reshape(\n args:\n {inputs: ReshapeInputs, backend: MathBackendCPU, attrs: ReshapeAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {shape} = attrs;\n\n const xSize = util.sizeFromShape(x.shape);\n const $shape = util.inferFromImplicitShape(shape, xSize);\n const $xSize = util.sizeFromShape($shape);\n\n util.assert(\n xSize === $xSize,\n () => `The new shape (${$shape}) has ${$xSize} elements and the old ` +\n `shape (${x.shape}) has ${xSize} elements. The new shape and old ` +\n `shape must have the same number of elements.`);\n\n backend.incRef(x.dataId);\n\n const xData = backend.data.get(x.dataId);\n\n if (xData.complexTensorInfos != null) {\n const real = xData.complexTensorInfos.real;\n const imag = xData.complexTensorInfos.imag;\n\n real.shape = $shape;\n imag.shape = $shape;\n }\n\n return {dataId: x.dataId, shape: $shape, dtype: x.dtype};\n}\n\nexport const reshapeConfig: KernelConfig = {\n kernelName: Reshape,\n backendName: 'cpu',\n kernelFunc: reshape as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs, broadcast_util, buffer, KernelConfig, KernelFunc, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {reshape} from './Reshape';\n\nexport function batchMatMul(args: {\n inputs: BatchMatMulInputs,\n attrs: BatchMatMulAttrs,\n backend: MathBackendCPU\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b} = inputs;\n const {transposeA, transposeB} = attrs;\n\n assertNotComplex([a, b], 'matMul');\n\n const aRank = a.shape.length;\n const bRank = b.shape.length;\n\n const innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];\n const innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];\n\n const outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];\n const outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];\n\n const outerDimsA = a.shape.slice(0, -2);\n const outerDimsB = b.shape.slice(0, -2);\n\n const batchDimA = util.sizeFromShape(outerDimsA);\n const batchDimB = util.sizeFromShape(outerDimsB);\n\n const outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n a.shape.slice(0, -2), b.shape.slice(0, -2));\n const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${a.shape} and ` +\n `${b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const a3dShape = transposeA ? [batchDimA, innerShapeA, outerShapeA] :\n [batchDimA, outerShapeA, innerShapeA];\n const b3dShape = transposeB ? [batchDimB, outerShapeB, innerShapeB] :\n [batchDimB, innerShapeB, outerShapeB];\n\n // The rest of the implementation is designed to operate on rank-3 tensors\n const a3d = reshape({inputs: {x: a}, backend, attrs: {shape: a3dShape}});\n const b3d = reshape({inputs: {x: b}, backend, attrs: {shape: b3dShape}});\n\n const sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];\n const leftDim = transposeA ? a3d.shape[2] : a3d.shape[1];\n const rightDim = transposeB ? b3d.shape[1] : b3d.shape[2];\n const batchDim = Math.max(batchDimA, batchDimB);\n\n const a3dValues = backend.data.get(a3d.dataId).values as TypedArray;\n const b3dValues = backend.data.get(b3d.dataId).values as TypedArray;\n\n const a3dStrides = util.computeStrides(a3d.shape);\n const b3dStrides = util.computeStrides(b3d.shape);\n\n const [aBatch, aOuterStep, aInnerStep] = transposeA ?\n [a3dStrides[0], 1, a3dStrides[1]] :\n [a3dStrides[0], a3dStrides[1], 1];\n const [bInnerStep, bOuterStep, bBatch] = transposeB ?\n [1, b3dStrides[1], b3dStrides[0]] :\n [b3dStrides[1], 1, b3dStrides[0]];\n\n const size = leftDim * rightDim;\n const result = buffer([batchDim, leftDim, rightDim], a3d.dtype);\n\n const resVals = result.values as TypedArray;\n const blockSize = backend.blockSize;\n\n for (let bi = 0; bi < batchDim; bi++) {\n const batchIndexA = bi % batchDimA;\n const batchIndexB = bi % batchDimB;\n for (let i0 = 0; i0 < leftDim; i0 += blockSize) {\n // for when blockSize doesn't evenly divide the input\n const iBlock = Math.min(i0 + blockSize, leftDim);\n for (let j0 = 0; j0 < rightDim; j0 += blockSize) {\n const jBlock = Math.min(j0 + blockSize, rightDim);\n for (let k0 = 0; k0 < sharedDim; k0 += blockSize) {\n const kBlock = Math.min(k0 + blockSize, sharedDim);\n\n for (let i = i0; i < iBlock; i++) {\n for (let j = j0; j < jBlock; j++) {\n let sum = 0.0;\n\n for (let k = k0; k < kBlock; k++) {\n const aVal =\n // tslint:disable-next-line: max-line-length\n a3dValues[batchIndexA * aBatch + i * aOuterStep + k * aInnerStep];\n const bVal =\n // tslint:disable-next-line: max-line-length\n b3dValues[k * bInnerStep + j * bOuterStep + batchIndexB * bBatch];\n sum += aVal * bVal;\n }\n resVals[bi * size + (i * rightDim + j)] += sum;\n }\n }\n }\n }\n }\n }\n\n backend.disposeIntermediateTensorInfo(a3d);\n backend.disposeIntermediateTensorInfo(b3d);\n\n // set correct shape on output.\n return backend.makeTensorInfo(\n outShape, result.dtype, result.values as TypedArray);\n}\n\nexport const batchMatMulConfig: KernelConfig = {\n kernelName: BatchMatMul,\n backendName: 'cpu',\n kernelFunc: batchMatMul as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {applyActivation} from '../utils/fused_utils';\n\nimport {add} from './Add';\nimport {batchMatMul} from './BatchMatMul';\n\nexport function _fusedMatMul(args: {\n inputs: _FusedMatMulInputs,\n attrs: _FusedMatMulAttrs,\n backend: MathBackendCPU\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b, bias, preluActivationWeights} = inputs;\n const {transposeA, transposeB, activation, leakyreluAlpha} = attrs;\n\n let current;\n let addRes;\n let activationRes;\n\n const intermediates: TensorInfo[] = [];\n\n const matMulRes =\n batchMatMul({inputs: {a, b}, attrs: {transposeA, transposeB}, backend});\n current = matMulRes;\n\n if (bias) {\n addRes = add({inputs: {a: current, b: bias}, backend}) as TensorInfo;\n intermediates.push(current);\n current = addRes;\n }\n if (activation) {\n activationRes = applyActivation(\n backend, current, activation, preluActivationWeights, leakyreluAlpha);\n intermediates.push(current);\n current = activationRes;\n }\n\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return current;\n}\n\nexport const _fusedMatMulConfig: KernelConfig = {\n kernelName: _FusedMatMul,\n backendName: 'cpu',\n kernelFunc: _fusedMatMul as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Acos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const acos = unaryKernelFunc(Acos, (xi) => Math.acos(xi));\n\nexport const acosConfig: KernelConfig = {\n kernelName: Acos,\n backendName: 'cpu',\n kernelFunc: acos,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Acosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const acosh = unaryKernelFunc(Acosh, (xi) => Math.acosh(xi));\n\nexport const acoshConfig: KernelConfig = {\n kernelName: Acosh,\n backendName: 'cpu',\n kernelFunc: acosh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AddN, AddNInputs, buffer, KernelConfig, KernelFunc, Tensor, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function addN(args: {inputs: AddNInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const tensors = inputs as Tensor[];\n\n assertNotComplex(inputs, 'addN');\n\n const vals =\n tensors.map(t => backend.data.get(t.dataId).values as TypedArray);\n const outBuf = buffer(tensors[0].shape, tensors[0].dtype as 'float32');\n const outVals = outBuf.values;\n for (let i = 0; i < tensors.length; i++) {\n const currVals = vals[i];\n for (let j = 0; j < outVals.length; j++) {\n outVals[j] += currVals[j];\n }\n }\n\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const addNConfig: KernelConfig = {\n kernelName: AddN,\n backendName: 'cpu',\n kernelFunc: addN as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {All, AllAttrs, AllInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function all(\n args: {inputs: AllInputs, backend: MathBackendCPU, attrs: AllAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'all');\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('all', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = util.makeZerosTypedArray(util.sizeFromShape(outShape), $x.dtype);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let all = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n all = all && value;\n }\n vals[i] = all;\n }\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo($x);\n }\n\n const result = backend.makeTensorInfo(outShape, $x.dtype, vals);\n\n if (keepDims) {\n const expandedShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n const reshapedResult =\n reshape({inputs: {x: result}, backend, attrs: {shape: expandedShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n }\n\n return result;\n}\n\nexport const allConfig: KernelConfig = {\n kernelName: All,\n backendName: 'cpu',\n kernelFunc: all as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Any, AnyAttrs, AnyInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function any(\n args: {inputs: AnyInputs, backend: MathBackendCPU, attrs: AnyAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'any');\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('any', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = util.makeZerosTypedArray(util.sizeFromShape(outShape), $x.dtype);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let anyVal = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n anyVal = anyVal || value;\n }\n vals[i] = anyVal;\n }\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo($x);\n }\n\n const result = backend.makeTensorInfo(outShape, $x.dtype, vals);\n\n if (keepDims) {\n const expandedShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n const reshapedResult =\n reshape({inputs: {x: result}, backend, attrs: {shape: expandedShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n }\n\n return result;\n}\n\nexport const anyConfig: KernelConfig = {\n kernelName: Any,\n backendName: 'cpu',\n kernelFunc: any as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ArgMax, ArgMaxAttrs, ArgMaxInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function argMax(\n args: {inputs: ArgMaxInputs, backend: MathBackendCPU, attrs: ArgMaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n assertNotComplex(x, 'argMax');\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n axes = [axes[0]];\n backend_util.assertAxesAreInnerMostDims('argMax', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n\n const outSize = util.sizeFromShape(outShape);\n const vals = util.makeZerosTypedArray(outSize, 'int32');\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let max = aVals[offset];\n let maxIndex = 0;\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (value > max) {\n max = value;\n maxIndex = j;\n }\n }\n vals[i] = maxIndex;\n }\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(outShape, 'int32', vals);\n}\n\nexport const argMaxConfig: KernelConfig = {\n kernelName: ArgMax,\n backendName: 'cpu',\n kernelFunc: argMax as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ArgMin, ArgMinAttrs, ArgMinInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function argMin(\n args: {inputs: ArgMinInputs, backend: MathBackendCPU, attrs: ArgMinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n assertNotComplex(x, 'argMin');\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n axes = [axes[0]];\n backend_util.assertAxesAreInnerMostDims('argMin', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n\n const outSize = util.sizeFromShape(outShape);\n const vals = util.makeZerosTypedArray(outSize, 'int32');\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let min = aVals[offset];\n let minIndex = 0;\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (value < min) {\n min = value;\n minIndex = j;\n }\n }\n vals[i] = minIndex;\n }\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(outShape, 'int32', vals);\n}\n\nexport const argMinConfig: KernelConfig = {\n kernelName: ArgMin,\n backendName: 'cpu',\n kernelFunc: argMin as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Asin, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const asin = unaryKernelFunc(Asin, (xi) => Math.asin(xi));\n\nexport const asinConfig: KernelConfig = {\n kernelName: Asin,\n backendName: 'cpu',\n kernelFunc: asin,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Asinh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const asinh = unaryKernelFunc(Asinh, (xi) => Math.asinh(xi));\n\nexport const asinhConfig: KernelConfig = {\n kernelName: Asinh,\n backendName: 'cpu',\n kernelFunc: asinh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atan, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const atan = unaryKernelFunc(Atan, (xi) => Math.atan(xi));\n\nexport const atanConfig: KernelConfig = {\n kernelName: Atan,\n backendName: 'cpu',\n kernelFunc: atan,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atan2, KernelConfig} from '@tensorflow/tfjs-core';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const atan2Impl = createSimpleBinaryKernelImpl(\n (aValue, bValue) => Math.atan2(aValue as number, bValue as number));\n\nexport const atan2 = binaryKernelFunc(Atan2, atan2Impl);\n\nexport const atan2Config: KernelConfig = {\n kernelName: Atan2,\n backendName: 'cpu',\n kernelFunc: atan2,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atanh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const atanh = unaryKernelFunc(Atanh, (xi) => Math.atanh(xi));\n\nexport const atanhConfig: KernelConfig = {\n kernelName: Atanh,\n backendName: 'cpu',\n kernelFunc: atanh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, buffer, DataType, Rank, TensorBuffer, TypedArray} from '@tensorflow/tfjs-core';\n\nexport function pool(\n xValues: TypedArray, xShape: number[], dtype: DataType, strides: number[],\n convInfo: backend_util.Conv2DInfo,\n poolType: 'max'|'avg'): TensorBuffer {\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 {\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 // For some reason, disable-next-line is not working\n // TODO(mattsoulanille): Remove this when switching to TS5.\n /* tslint:disable: no-unnecessary-type-assertion */\n const pixel = xBuf.get(b, xR, xC, d) as number;\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 {\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] = poolType === 'avg' ?\n avgValue / Math.max(count, 1) :\n minMaxValue;\n }\n }\n }\n }\n }\n\n return output;\n}\n\nexport function maxPool3dPositions(\n xBuf: TensorBuffer,\n convInfo: backend_util.Conv3DInfo): TensorBuffer {\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,\n channel) as number;\n if (pixel >= maxValue) {\n maxValue = pixel as number;\n maxPosition =\n wDepth * effectiveFilterHeight * effectiveFilterWidth +\n wRow * effectiveFilterHeight + wCol;\n }\n }\n }\n }\n\n maxPositions.set(maxPosition, batch, yDepth, yRow, yCol, channel);\n }\n }\n }\n }\n }\n\n return maxPositions;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPool, AvgPoolAttrs, AvgPoolInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool} from '../utils/pool_utils';\nimport {identity} from './Identity';\n\nexport function avgPool(\n args:\n {inputs: AvgPoolInputs, backend: MathBackendCPU, attrs: AvgPoolAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'avgPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n let res: TensorInfo;\n\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n res = identity({inputs: {x}, backend});\n } else {\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const strides = util.computeStrides(x.shape);\n const buffer = pool(xValues, x.shape, x.dtype, strides, convInfo, 'avg');\n res = backend.makeTensorInfo(\n convInfo.outShape, x.dtype, buffer.values as TypedArray);\n }\n return res;\n}\n\nexport const avgPoolConfig: KernelConfig = {\n kernelName: AvgPool,\n backendName: 'cpu',\n kernelFunc: avgPool as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool3d} from '../utils/pool_utils';\n\nexport function avgPool3D(args: {\n inputs: AvgPool3DInputs,\n backend: MathBackendCPU,\n attrs: AvgPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dimRoundingMode, dataFormat} = attrs;\n\n assertNotComplex(x, 'avgPool3d');\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode, dataFormat);\n\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const outBuf = pool3d(\n xValues, x.shape, x.dtype, util.computeStrides(x.shape), convInfo, 'avg');\n\n return backend.makeTensorInfo(outBuf.shape, 'float32', outBuf.values);\n}\n\nexport const avgPool3DConfig: KernelConfig = {\n kernelName: AvgPool3D,\n backendName: 'cpu',\n kernelFunc: avgPool3D as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AvgPool3DGrad, AvgPool3DGradAttrs, AvgPool3DGradInputs, backend_util, buffer, KernelConfig, KernelFunc, Rank, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function avgPool3DGrad(args: {\n inputs: AvgPool3DGradInputs,\n backend: MathBackendCPU,\n attrs: AvgPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n assertNotComplex([dy, input], 'avgPool3DGrad');\n\n const convInfo = backend_util.computePool3DInfo(\n input.shape as [number, number, number, number, number], filterSize,\n strides, 1 /* dilations */, pad, dimRoundingMode);\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx = buffer(input.shape, 'float32');\n\n const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);\n\n const dyBuf = backend.bufferSync(dy);\n\n for (let batch = 0; batch < convInfo.batchSize; ++batch) {\n for (let channel = 0; channel < convInfo.inChannels; ++channel) {\n for (let dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {\n for (let dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {\n for (let dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {\n // Shader code begins.\n const dyDepthCorner = dxDepth - padFront;\n const dyRowCorner = dxRow - padTop;\n const dyColCorner = dxCol - padLeft;\n let dotProd = 0;\n for (let wDepth = 0; wDepth < effectiveFilterDepth;\n wDepth += dilationDepth) {\n const dyDepth = (dyDepthCorner + wDepth) / strideDepth;\n if (dyDepth < 0 || dyDepth >= convInfo.outDepth ||\n Math.floor(dyDepth) !== dyDepth) {\n continue;\n }\n for (let wRow = 0; wRow < effectiveFilterHeight;\n wRow += dilationHeight) {\n const dyRow = (dyRowCorner + wRow) / strideHeight;\n if (dyRow < 0 || dyRow >= convInfo.outHeight ||\n Math.floor(dyRow) !== dyRow) {\n continue;\n }\n for (let wCol = 0; wCol < effectiveFilterWidth;\n wCol += dilationWidth) {\n const dyCol = (dyColCorner + wCol) / strideWidth;\n if (dyCol < 0 || dyCol >= convInfo.outWidth ||\n Math.floor(dyCol) !== dyCol) {\n continue;\n }\n\n const pixel =\n dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);\n dotProd += pixel;\n }\n }\n }\n dx.set(\n dotProd * avgMultiplier, batch, dxDepth, dxRow, dxCol, channel);\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const avgPool3DGradConfig: KernelConfig = {\n kernelName: AvgPool3DGrad,\n backendName: 'cpu',\n kernelFunc: avgPool3DGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPoolGrad, AvgPoolGradAttrs, AvgPoolGradInputs, backend_util, buffer, KernelConfig, KernelFunc, Rank, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function avgPoolGrad(args: {\n inputs: AvgPoolGradInputs,\n backend: MathBackendCPU,\n attrs: AvgPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n assertNotComplex([dy, input], 'avgPoolGrad');\n const {filterSize, strides, pad} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad);\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx =\n buffer(x.shape as [number, number, number, number], 'float32');\n\n const avgMultiplier = 1 / (filterHeight * filterWidth);\n\n const dyData = backend.data.get(dy.dataId).values as Float32Array;\n const dyBuf = buffer(\n dy.shape as [number, number, number, number], 'float32', dyData);\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let d = 0; d < convInfo.inChannels; ++d) {\n for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {\n for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {\n // Shader code begins.\n const dyRCorner = dxR - padTop;\n const dyCCorner = dxC - padLeft;\n let dotProd = 0;\n for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {\n const dyR = (dyRCorner + wR) / strideHeight;\n if (dyR < 0 || dyR >= convInfo.outHeight ||\n Math.floor(dyR) !== dyR) {\n continue;\n }\n for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {\n const dyC = (dyCCorner + wC) / strideWidth;\n if (dyC < 0 || dyC >= convInfo.outWidth ||\n Math.floor(dyC) !== dyC) {\n continue;\n }\n\n const pixel = dyBuf.get(b, dyR, dyC, d);\n dotProd += pixel;\n }\n }\n dx.set(dotProd * avgMultiplier, b, dxR, dxC, d);\n }\n }\n }\n }\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const avgPoolGradConfig: KernelConfig = {\n kernelName: AvgPoolGrad,\n backendName: 'cpu',\n kernelFunc: avgPoolGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function batchNorm(args: {\n inputs: FusedBatchNormInputs,\n backend: MathBackendCPU,\n attrs: FusedBatchNormAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, scale, offset, mean, variance} = inputs;\n\n util.assert(\n mean.shape.length === variance.shape.length,\n () => 'Batch normalization gradient requires mean and variance to have ' +\n 'equal ranks.');\n util.assert(\n offset == null || mean.shape.length === offset.shape.length,\n () => 'Batch normalization gradient requires mean and offset to have ' +\n 'equal ranks.');\n util.assert(\n scale == null || mean.shape.length === scale.shape.length,\n () => 'Batch normalization gradient requires mean and scale to have ' +\n 'equal ranks.');\n\n assertNotComplex([x, mean, variance, scale, offset], 'batchNorm');\n\n let {varianceEpsilon} = attrs;\n if (varianceEpsilon == null) {\n varianceEpsilon = 0.001;\n }\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const mVals = backend.data.get(mean.dataId).values as TypedArray;\n const varVals = backend.data.get(variance.dataId).values as TypedArray;\n const sVals = scale ? backend.data.get(scale.dataId).values as TypedArray :\n new Float32Array([1]);\n const offVals = offset ?\n backend.data.get(offset.dataId).values as TypedArray :\n new Float32Array([0]);\n const outVals = new Float32Array(xVals.length);\n\n const offValsLength = offVals.length;\n const sValsLength = sVals.length;\n const varValsLength = varVals.length;\n const mValsLength = mVals.length;\n\n let offi = 0;\n let mi = 0;\n let si = 0;\n let vi = 0;\n for (let i = 0; i < xVals.length; ++i) {\n outVals[i] = offVals[offi++] +\n (xVals[i] - mVals[mi++]) * sVals[si++] /\n Math.sqrt(varVals[vi++] + varianceEpsilon);\n if (offi >= offValsLength) {\n offi = 0;\n }\n if (mi >= mValsLength) {\n mi = 0;\n }\n if (si >= sValsLength) {\n si = 0;\n }\n if (vi >= varValsLength) {\n vi = 0;\n }\n }\n return backend.makeTensorInfo(x.shape, x.dtype, outVals);\n}\n\nexport const batchNormConfig: KernelConfig = {\n kernelName: FusedBatchNorm,\n backendName: 'cpu',\n kernelFunc: batchNorm as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {transpose} from './Transpose';\n\nexport function batchToSpaceND(args: {\n inputs: BatchToSpaceNDInputs,\n backend: MathBackendCPU,\n attrs: BatchToSpaceNDAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, crops} = attrs;\n\n assertNotComplex([x], 'batchToSpaceND');\n\n const prod = blockShape.reduce((a, b) => a * b);\n\n const reshaped = backend_util.getReshaped(x.shape, blockShape, prod);\n const permuted = backend_util.getPermuted(reshaped.length, blockShape.length);\n const reshapedPermuted =\n backend_util.getReshapedPermuted(x.shape, blockShape, prod);\n const sliceBeginCoords =\n backend_util.getSliceBeginCoords(crops, blockShape.length);\n const sliceSize =\n backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);\n\n const xReshaped = reshape({inputs: {x}, backend, attrs: {shape: reshaped}});\n const xTransposed =\n transpose({inputs: {x: xReshaped}, backend, attrs: {perm: permuted}});\n const xTransposedReshaped = reshape(\n {inputs: {x: xTransposed}, backend, attrs: {shape: reshapedPermuted}});\n const result = slice({\n inputs: {x: xTransposedReshaped},\n backend,\n attrs: {begin: sliceBeginCoords, size: sliceSize}\n });\n\n backend.disposeIntermediateTensorInfo(xReshaped);\n backend.disposeIntermediateTensorInfo(xTransposed);\n backend.disposeIntermediateTensorInfo(xTransposedReshaped);\n\n return result;\n}\n\nexport const batchToSpaceNDConfig: KernelConfig = {\n kernelName: BatchToSpaceND,\n backendName: 'cpu',\n kernelFunc: batchToSpaceND as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Bincount, BincountAttrs, BincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {bincountImpl} from './Bincount_impl';\n\nexport function bincount(args: {\n inputs: BincountInputs,\n backend: MathBackendCPU,\n attrs: BincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size} = attrs;\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const weightsVals = backend.data.get(weights.dataId).values as TypedArray;\n\n const outVals =\n bincountImpl(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n}\n\nexport const bincountConfig: KernelConfig = {\n kernelName: Bincount,\n backendName: 'cpu',\n kernelFunc: bincount as unknown 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, BroadcastArgs, BroadcastArgsInputs, KernelConfig, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function broadcastArgs(args: {\n inputs: BroadcastArgsInputs,\n backend: MathBackendCPU,\n}): TensorInfo {\n const {inputs, backend} = args;\n const {s0, s1} = inputs;\n\n const s0Vals = backend.data.get(s0.dataId).values as TypedArray;\n const s1Vals = backend.data.get(s1.dataId).values as TypedArray;\n\n const broadcastShape = backend_util.assertAndGetBroadcastShape(\n Array.from(s0Vals), Array.from(s1Vals));\n\n return backend.makeTensorInfo(\n [broadcastShape.length], 'int32', Int32Array.from(broadcastShape));\n}\n\nexport const broadcastArgsConfig: KernelConfig = {\n kernelName: BroadcastArgs,\n backendName: 'cpu',\n kernelFunc: broadcastArgs\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 clipByValue = unaryKernelFunc(ClipByValue, (xi, attrs) => {\n const clipAttrs = attrs as unknown as ClipByValueAttrs;\n if (xi > clipAttrs.clipValueMax) {\n return clipAttrs.clipValueMax;\n }\n return xi < clipAttrs.clipValueMin ? clipAttrs.clipValueMin : xi;\n});\n\nexport const clipByValueConfig: KernelConfig = {\n kernelName: ClipByValue,\n backendName: 'cpu',\n kernelFunc: clipByValue,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ComplexAbs, ComplexAbsInputs, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const complexAbs =\n (args: {inputs: ComplexAbsInputs, backend: MathBackendCPU}) => {\n const {x} = args.inputs;\n const cpuBackend = args.backend;\n const resultValues = new Float32Array(util.sizeFromShape(x.shape));\n const complexVals = cpuBackend.data.get(x.dataId);\n const real = complexVals.complexTensorInfos.real;\n const imag = complexVals.complexTensorInfos.imag;\n const realVals = cpuBackend.data.get(real.dataId).values as Float32Array;\n const imagVals = cpuBackend.data.get(imag.dataId).values as Float32Array;\n for (let i = 0; i < realVals.length; i++) {\n const real = realVals[i];\n const imag = imagVals[i];\n resultValues[i] = Math.hypot(real, imag);\n }\n\n return cpuBackend.makeOutput(resultValues, x.shape, 'float32');\n };\n\nexport const complexAbsConfig: KernelConfig = {\n kernelName: ComplexAbs,\n backendName: 'cpu',\n kernelFunc: complexAbs as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Imag, ImagInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function imag(args: {inputs: ImagInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n const imag = backend.data.get(input.dataId).complexTensorInfos.imag;\n const imagVal = backend.data.get(imag.dataId).values;\n\n // When complex tensor is disposed, its underlying parts will be disposed too.\n // Make new tensor out of the imag value of the complex. This makes sure the\n // value is still accessible even if complex tensor is disposed.\n return backend.makeTensorInfo(imag.shape, imag.dtype, imagVal);\n}\n\nexport const imagConfig: KernelConfig = {\n kernelName: Imag,\n backendName: 'cpu',\n kernelFunc: imag as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Concat, ConcatAttrs, ConcatInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {complex} from './Complex';\nimport {concatImpl} from './Concat_impl';\nimport {identity} from './Identity';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {reshape} from './Reshape';\n\nexport function concat(\n args: {inputs: ConcatInputs, backend: MathBackendCPU, attrs: ConcatAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, inputs[0].shape)[0];\n\n const shapes = inputs.map(t => t.shape);\n backend_util.assertParamsConsistent(shapes, $axis);\n\n let outShape = backend_util.computeOutShape(inputs.map(t => t.shape), $axis);\n\n if (util.sizeFromShape(outShape) === 0) {\n return backend.makeTensorInfo(outShape, inputs[0].dtype, []);\n }\n\n // Keep only non-empty tensors (ignore tensors with 0 in their shape).\n const $inputs = inputs.filter(t => util.sizeFromShape(t.shape) > 0);\n if ($inputs.length === 1) {\n return identity({inputs: {x: $inputs[0]}, backend});\n }\n\n if ($inputs[0].dtype === 'complex64') {\n const reals = $inputs.map((t) => real({inputs: {input: t}, backend}));\n const imags = $inputs.map((t) => imag({inputs: {input: t}, backend}));\n\n const realConcated = concat({inputs: reals, backend, attrs: {axis: $axis}});\n const imagConcated = concat({inputs: imags, backend, attrs: {axis: $axis}});\n\n const result =\n complex({inputs: {real: realConcated, imag: imagConcated}, backend});\n\n reals.forEach(r => backend.disposeIntermediateTensorInfo(r));\n imags.forEach(i => backend.disposeIntermediateTensorInfo(i));\n backend.disposeIntermediateTensorInfo(realConcated);\n backend.disposeIntermediateTensorInfo(imagConcated);\n\n return result;\n }\n\n // Any concat of n-dimensional tensors across any axis can be reduced to\n // a concatenation of two-dimensional tensors across the axis 1 by first\n // partitioning the axes of the original tensors into those less than the\n // axis to be concatenated and the rest. Then reshape the tensors\n // into a two-dimensional tensor by collapsing these two sets of axes and\n // concatenate the resulting matrices across the axis 1, finally reshaping\n // the result to have the proper shape.\n const inputs2D = $inputs.map(t => {\n const innerSize = util.sizeFromShape(t.shape.slice($axis));\n const shape = [-1, innerSize];\n return reshape({inputs: {x: t}, backend, attrs: {shape}});\n });\n\n const inputsValShapes = inputs2D.map(t => {\n return {vals: backend.data.get(t.dataId).values, shape: t.shape};\n });\n\n // Concats 2d tensors along axis=1.\n outShape =\n backend_util.computeOutShape(inputs2D.map(t => t.shape), 1 /* axis */);\n const simplyConcat = inputs2D[0].shape[0] === 1;\n const outVals =\n concatImpl(inputsValShapes, outShape, inputs[0].dtype, simplyConcat);\n\n const finalOutShape =\n backend_util.computeOutShape($inputs.map(t => t.shape), $axis);\n\n const outInfo =\n backend.makeTensorInfo(finalOutShape, inputs[0].dtype, outVals);\n\n inputs2D.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return outInfo;\n}\n\nexport const concatConfig: KernelConfig = {\n kernelName: Concat,\n backendName: 'cpu',\n kernelFunc: concat as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2D, Conv2DAttrs, Conv2DInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv2D(\n args: {inputs: Conv2DInputs, backend: MathBackendCPU, attrs: Conv2DAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dataFormat, dilations, dimRoundingMode} = attrs;\n\n assertNotComplex([x, filter], 'conv2d');\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, dilations, pad,\n dimRoundingMode, false /* depthwise */, $dataFormat);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const padLeft = convInfo.padInfo.left;\n const padTop = convInfo.padInfo.top;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const y = new TensorBuffer(convInfo.outShape, x.dtype as 'float32');\n\n const xStrides = util.computeStrides(x.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n const xBatchStride = xStrides[0];\n const xRowStride = isChannelsLast ? xStrides[1] : xStrides[2];\n const xColStride = isChannelsLast ? xStrides[2] : 1;\n const xChannelStride = isChannelsLast ? 1 : xStrides[1];\n const yBatchStride = y.strides[0];\n const yRowStride = isChannelsLast ? y.strides[1] : y.strides[2];\n const yColStride = isChannelsLast ? y.strides[2] : 1;\n const yChannelStride = isChannelsLast ? 1 : y.strides[1];\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const wVals = backend.data.get(filter.dataId).values as TypedArray;\n const yVals = y.values;\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xBatchStride;\n const yOffset1 = b * yBatchStride;\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const yOffset2 = yOffset1 + yR * yRowStride;\n const xRCorner = yR * convInfo.strideHeight - padTop;\n for (let wR = 0; wR < filterHeight; ++wR) {\n const xR = xRCorner + wR * dilationHeight;\n if (xR < 0 || xR >= convInfo.inHeight) {\n continue;\n }\n const wOffset1 = wR * filterStrides[0];\n const xOffset2 = xOffset1 + xR * xRowStride;\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const yOffset3 = yOffset2 + yC * yColStride;\n const xCCorner = yC * convInfo.strideWidth - padLeft;\n for (let wC = 0; wC < filterWidth; ++wC) {\n const xC = xCCorner + wC * dilationWidth;\n if (xC < 0 || xC >= convInfo.inWidth) {\n continue;\n }\n const wOffset2 = wOffset1 + wC * filterStrides[1];\n const xOffset3 = xOffset2 + xC * xColStride;\n let wOffset3 = wOffset2;\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const xVal = xVals[xOffset3 + d1 * xChannelStride];\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n yVals[yOffset3 + d2 * yChannelStride] +=\n xVal * wVals[wOffset3 + d2];\n }\n wOffset3 += convInfo.outChannels;\n }\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(y.shape, y.dtype, yVals);\n}\n\nexport const conv2DConfig: KernelConfig = {\n kernelName: Conv2D,\n backendName: 'cpu',\n kernelFunc: conv2D as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv2DBackpropFilter(args: {\n inputs: Conv2DBackpropFilterInputs,\n backend: MathBackendCPU,\n attrs: Conv2DBackpropFilterAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, dataFormat, dimRoundingMode, filterShape} = attrs;\n\n assertNotComplex([x, dy], 'conv2dBackpropFilter');\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad, dimRoundingMode, false /* depthwise */,\n $dataFormat);\n\n const {strideHeight, strideWidth, filterHeight, filterWidth} = convInfo;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n const dW = new TensorBuffer(convInfo.filterShape, 'float32');\n\n const leftPad = convInfo.padInfo.left;\n const topPad = convInfo.padInfo.top;\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const dyVals = backend.data.get(dy.dataId).values as TypedArray;\n\n const xBuf = new TensorBuffer(x.shape, x.dtype, xVals);\n const dyBuf = new TensorBuffer(dy.shape, dy.dtype, dyVals);\n\n for (let wR = 0; wR < filterHeight; ++wR) {\n const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));\n const yRMax = Math.min(\n convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);\n\n for (let wC = 0; wC < filterWidth; ++wC) {\n const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));\n const yCMax = Math.min(\n convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);\n\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n let dotProd = 0;\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let yR = yRMin; yR < yRMax; ++yR) {\n const xR = wR + yR * strideHeight - topPad;\n for (let yC = yCMin; yC < yCMax; ++yC) {\n const xC = wC + yC * strideWidth - leftPad;\n if (isChannelsLast) {\n dotProd += (xBuf.get(b, xR, xC, d1) as number) *\n (dyBuf.get(b, yR, yC, d2) as number);\n } else {\n dotProd += (xBuf.get(b, d1, xR, xC) as number) *\n (dyBuf.get(b, d2, yR, yC) as number);\n }\n }\n }\n }\n dW.set(dotProd, wR, wC, d1, d2);\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);\n}\n\nexport const conv2DBackpropFilterConfig: KernelConfig = {\n kernelName: Conv2DBackpropFilter,\n backendName: 'cpu',\n kernelFunc: conv2DBackpropFilter as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv2DBackpropInput(args: {\n inputs: Conv2DBackpropInputInputs,\n backend: MathBackendCPU,\n attrs: Conv2DBackpropInputAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {inputShape, strides, pad, dataFormat, dimRoundingMode} = attrs;\n\n assertNotComplex([dy, filter], 'conv2dBackpropInput');\n\n const filterStrides = util.computeStrides(filter.shape);\n const dyStrides = util.computeStrides(dy.shape);\n\n let $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n 1 /* dilations */, pad, dimRoundingMode, false, $dataFormat);\n\n const dx = new TensorBuffer(convInfo.inShape, 'float32');\n const dxValues = dx.values;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const fltValues = backend.data.get(filter.dataId).values as TypedArray;\n const [fltS0, fltS1, fltS2] = filterStrides;\n const {\n batchSize,\n filterHeight,\n filterWidth,\n inChannels,\n inHeight,\n inWidth,\n outChannels,\n outHeight,\n outWidth,\n strideHeight,\n strideWidth\n } = convInfo;\n $dataFormat = convInfo.dataFormat;\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n\n const isChannelsLast = $dataFormat === 'channelsLast';\n const xBatchStride = dx.strides[0];\n const xRowStride = isChannelsLast ? dx.strides[1] : dx.strides[2];\n const xColStride = isChannelsLast ? dx.strides[2] : 1;\n const xChannelStride = isChannelsLast ? 1 : dx.strides[1];\n const yBatchStride = dyStrides[0];\n const yRowStride = isChannelsLast ? dyStrides[1] : dyStrides[2];\n const yColStride = isChannelsLast ? dyStrides[2] : 1;\n const yChannelStride = isChannelsLast ? 1 : dyStrides[1];\n\n for (let b = 0; b < batchSize; ++b) {\n for (let d1 = 0; d1 < inChannels; ++d1) {\n for (let xR = 0; xR < inHeight; ++xR) {\n const xRCorner = xR - topPad;\n const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));\n const yRMax =\n Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);\n\n for (let xC = 0; xC < inWidth; ++xC) {\n const xCCorner = xC - leftPad;\n const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));\n const yCMax =\n Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);\n\n let dotProd = 0;\n for (let yR = xRMin; yR < yRMax; ++yR) {\n const wR = yR * strideHeight - xRCorner;\n\n for (let yC = xCMin; yC < yCMax; ++yC) {\n const wC = yC * strideWidth - xCCorner;\n const dyOffset =\n yBatchStride * b + yRowStride * yR + yColStride * yC;\n const fltOffset = fltS0 * (filterHeight - 1 - wR) +\n fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;\n\n for (let d2 = 0; d2 < outChannels; ++d2) {\n const pixel = dyValues[dyOffset + yChannelStride * d2];\n const weight = fltValues[fltOffset + d2];\n dotProd += pixel * weight;\n }\n }\n }\n const dxOffset = xBatchStride * b + xRowStride * xR +\n xColStride * xC + xChannelStride * d1;\n dxValues[dxOffset] = dotProd;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const conv2DBackpropInputConfig: KernelConfig = {\n kernelName: Conv2DBackpropInput,\n backendName: 'cpu',\n kernelFunc: conv2DBackpropInput as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv3D, Conv3DAttrs, Conv3DInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv3D(\n args: {inputs: Conv3DInputs, backend: MathBackendCPU, attrs: Conv3DAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n assertNotComplex([x, filter], 'conv3d');\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number],\n filter.shape as [number, number, number, number, number], strides,\n dilations, pad);\n\n const {\n filterDepth,\n filterHeight,\n filterWidth,\n dilationDepth,\n dilationHeight,\n dilationWidth,\n padInfo\n } = convInfo;\n const padFront = padInfo.front;\n const padLeft = padInfo.left;\n const padTop = padInfo.top;\n const y = new TensorBuffer(convInfo.outShape, x.dtype as 'float32');\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const wVals = backend.data.get(filter.dataId).values as TypedArray;\n const yVals = y.values;\n\n const xStrides = util.computeStrides(x.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xStrides[0];\n const yOffset1 = b * y.strides[0];\n for (let yF = 0; yF < convInfo.outDepth; ++yF) {\n const yOffset2 = yOffset1 + yF * y.strides[1];\n const xFCorner = yF * convInfo.strideDepth - padFront;\n for (let wF = 0; wF < filterDepth; ++wF) {\n const xF = xFCorner + wF * dilationDepth;\n if (xF < 0 || xF >= convInfo.inDepth) {\n continue;\n }\n const wOffset1 = wF * filterStrides[0];\n const xOffset2 = xOffset1 + xF * xStrides[1];\n\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const yOffset3 = yOffset2 + yR * y.strides[2];\n const xRCorner = yR * convInfo.strideHeight - padTop;\n for (let wR = 0; wR < filterHeight; ++wR) {\n const xR = xRCorner + wR * dilationHeight;\n if (xR < 0 || xR >= convInfo.inHeight) {\n continue;\n }\n const wOffset2 = wOffset1 + wR * filterStrides[1];\n const xOffset3 = xOffset2 + xR * xStrides[2];\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const yOffset4 = yOffset3 + yC * convInfo.outChannels;\n const xCCorner = yC * convInfo.strideWidth - padLeft;\n for (let wC = 0; wC < filterWidth; ++wC) {\n const xC = xCCorner + wC * dilationWidth;\n if (xC < 0 || xC >= convInfo.inWidth) {\n continue;\n }\n const wOffset3 = wOffset2 + wC * filterStrides[2];\n const xOffset4 = xOffset3 + xC * convInfo.inChannels;\n let wOffset4 = wOffset3;\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const xVal = xVals[xOffset4 + d1];\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n yVals[yOffset4 + d2] += xVal * wVals[wOffset4 + d2];\n }\n wOffset4 += convInfo.outChannels;\n }\n }\n }\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(y.shape, y.dtype, y.values);\n}\n\nexport const conv3DConfig: KernelConfig = {\n kernelName: Conv3D,\n backendName: 'cpu',\n kernelFunc: conv3D as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv3DBackpropFilterV2, Conv3DBackpropFilterV2Attrs, Conv3DBackpropFilterV2Inputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv3DBackpropFilterV2(args: {\n inputs: Conv3DBackpropFilterV2Inputs,\n backend: MathBackendCPU,\n attrs: Conv3DBackpropFilterV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, filterShape} = attrs;\n\n assertNotComplex([x, dy], 'conv3dBackpropFilterV2');\n\n const xStrides = util.computeStrides(x.shape);\n const dyStrides = util.computeStrides(dy.shape);\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad);\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const dw = new TensorBuffer(convInfo.filterShape, 'float32');\n const dwValues = dw.values;\n const [dwS0, dwS1, dwS2, dwS3] = dw.strides;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const [dyS0, dyS1, dyS2, dyS3] = dyStrides;\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const [xS0, xS1, xS2, xS3] = xStrides;\n\n const frontPad = convInfo.padInfo.front;\n const leftPad = convInfo.padInfo.left;\n const topPad = convInfo.padInfo.top;\n\n for (let wF = 0; wF < filterDepth; ++wF) {\n const yFMin = Math.max(0, Math.ceil((frontPad - wF) / strideDepth));\n const yFMax = Math.min(\n convInfo.outDepth, (convInfo.inDepth + frontPad - wF) / strideDepth);\n const wOffset1 = wF * dwS0;\n\n for (let wR = 0; wR < filterHeight; ++wR) {\n const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));\n const yRMax = Math.min(\n convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);\n const wOffset2 = wR * dwS1 + wOffset1;\n\n for (let wC = 0; wC < filterWidth; ++wC) {\n const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));\n const yCMax = Math.min(\n convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);\n const wOffset3 = wC * dwS2 + wOffset2;\n\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const wOffset4 = d1 * dwS3 + wOffset3;\n\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n let dotProd = 0;\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xS0;\n const yOffset1 = b * dyS0;\n\n for (let yF = yFMin; yF < yFMax; ++yF) {\n const xF = wF + yF * strideDepth - frontPad;\n const xOffset2 = xF * xS1 + xOffset1;\n const yOffset2 = yF * dyS1 + yOffset1;\n\n for (let yR = yRMin; yR < yRMax; ++yR) {\n const xR = wR + yR * strideHeight - topPad;\n const xOffset3 = xR * xS2 + xOffset2;\n const yOffset3 = yR * dyS2 + yOffset2;\n\n for (let yC = yCMin; yC < yCMax; ++yC) {\n const xC = wC + yC * strideWidth - leftPad;\n const xOffset4 = xC * xS3 + xOffset3;\n const yOffset4 = yC * dyS3 + yOffset3;\n\n dotProd += xValues[xOffset4 + d1] * dyValues[yOffset4 + d2];\n }\n }\n }\n }\n dwValues[wOffset4 + d2] = dotProd;\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dw.shape, dw.dtype, dw.values);\n}\n\nexport const conv3DBackpropFilterV2Config: KernelConfig = {\n kernelName: Conv3DBackpropFilterV2,\n backendName: 'cpu',\n kernelFunc: conv3DBackpropFilterV2 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv3DBackpropInputV2(args: {\n inputs: Conv3DBackpropInputV2Inputs,\n backend: MathBackendCPU,\n attrs: Conv3DBackpropInputV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {pad, strides, inputShape} = attrs;\n\n assertNotComplex([dy], 'conv3dBackpropInputV2');\n\n const dyStrides = util.computeStrides(dy.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n const convInfo = backend_util.computeConv3DInfo(\n inputShape, filter.shape as [number, number, number, number, number],\n strides, 1 /* dilations */, pad);\n\n const dx = new TensorBuffer(convInfo.inShape, 'float32');\n const dxValues = dx.values;\n const [dxS0, dxS1, dxS2, dxS3] = dx.strides;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const [dyS0, dyS1, dyS2, dyS3] = dyStrides;\n const fltValues = backend.data.get(filter.dataId).values as TypedArray;\n const [fltS0, fltS1, fltS2, fltS3] = filterStrides;\n const {\n batchSize,\n filterDepth,\n filterHeight,\n filterWidth,\n inChannels,\n inDepth,\n inHeight,\n inWidth,\n outChannels,\n outDepth,\n outHeight,\n outWidth,\n strideDepth,\n strideHeight,\n strideWidth\n } = convInfo;\n const frontPad = filterDepth - 1 - convInfo.padInfo.front;\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n\n for (let b = 0; b < batchSize; ++b) {\n for (let d1 = 0; d1 < inChannels; ++d1) {\n // Frames of depth\n for (let xF = 0; xF < inDepth; ++xF) {\n const xFCorner = xF - frontPad;\n const xFMin = Math.max(0, Math.ceil(xFCorner / strideDepth));\n const yFMax =\n Math.min(outDepth, (filterDepth + xFCorner) / strideDepth);\n\n // Rows as per standard 2d matrix notation\n for (let xR = 0; xR < inHeight; ++xR) {\n const xRCorner = xR - topPad;\n const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));\n const yRMax =\n Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);\n // Columns as per standard 2d matrix notation\n for (let xC = 0; xC < inWidth; ++xC) {\n const xCCorner = xC - leftPad;\n const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));\n const yCMax =\n Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);\n\n let dotProd = 0;\n for (let yF = xFMin; yF < yFMax; ++yF) {\n const wF = yF * strideDepth - xFCorner;\n\n for (let yR = xRMin; yR < yRMax; ++yR) {\n const wR = yR * strideHeight - xRCorner;\n\n for (let yC = xCMin; yC < yCMax; ++yC) {\n const wC = yC * strideWidth - xCCorner;\n const dyOffset = dyS0 * b + dyS1 * yF + dyS2 * yR + dyS3 * yC;\n const fltOffset = fltS0 * (filterDepth - 1 - wF) +\n fltS1 * (filterHeight - 1 - wR) +\n fltS2 * (filterWidth - 1 - wC) + fltS3 * d1;\n\n for (let d2 = 0; d2 < outChannels; ++d2) {\n const pixel = dyValues[dyOffset + d2];\n const weight = fltValues[fltOffset + d2];\n dotProd += pixel * weight;\n }\n }\n }\n }\n dxValues[dxS0 * b + dxS1 * xF + dxS2 * xR + dxS3 * xC + d1] =\n dotProd;\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const conv3DBackpropInputV2Config: KernelConfig = {\n kernelName: Conv3DBackpropInputV2,\n backendName: 'cpu',\n kernelFunc: conv3DBackpropInputV2 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const cos = unaryKernelFunc(Cos, (xi) => Math.cos(xi));\n\nexport const cosConfig: KernelConfig = {\n kernelName: Cos,\n backendName: 'cpu',\n kernelFunc: cos,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const cosh = unaryKernelFunc(Cosh, (xi) => Math.cosh(xi));\n\nexport const coshConfig: KernelConfig = {\n kernelName: Cosh,\n backendName: 'cpu',\n kernelFunc: cosh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, CropAndResize, CropAndResizeAttrs, CropAndResizeInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function cropAndResize(args: {\n inputs: CropAndResizeInputs,\n backend: MathBackendCPU,\n attrs: CropAndResizeAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image, boxes, boxInd} = inputs;\n const {cropSize, method, extrapolationValue} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const numBoxes = boxes.shape[0];\n\n const [cropHeight, cropWidth] = cropSize;\n const output =\n buffer([numBoxes, cropHeight, cropWidth, numChannels], 'float32');\n\n const boxVals = backend.data.get(boxes.dataId).values as TypedArray;\n const boxIndVals = backend.data.get(boxInd.dataId).values as TypedArray;\n const imageVals = backend.data.get(image.dataId).values as TypedArray;\n\n const inStride =\n util.computeStrides(image.shape); // to calculate flat indexes into image\n const outStride = util.computeStrides(\n output.shape); // to calculate flat indexes into output\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op.cc\n for (let b = 0; b < numBoxes; b++) {\n const startInd = b * 4;\n const y1 = boxVals[startInd];\n const x1 = boxVals[startInd + 1];\n const y2 = boxVals[startInd + 2];\n const x2 = boxVals[startInd + 3];\n\n const bInd: number = boxIndVals[b];\n if (bInd >= batch) {\n continue;\n }\n\n const heightScale =\n (cropHeight > 1) ? (y2 - y1) * (imageHeight - 1) / (cropHeight - 1) : 0;\n const widthScale =\n (cropWidth > 1) ? (x2 - x1) * (imageWidth - 1) / (cropWidth - 1) : 0;\n\n for (let y = 0; y < cropHeight; y++) {\n const yInd: number = (cropHeight > 1) ?\n y1 * (imageHeight - 1) + y * (heightScale) :\n 0.5 * (y1 + y2) * (imageHeight - 1);\n\n if (yInd < 0 || yInd > imageHeight - 1) {\n for (let x = 0; x < cropWidth; x++) {\n for (let c = 0; c < numChannels; c++) {\n const ind =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = extrapolationValue;\n }\n }\n continue;\n }\n\n if (method === 'bilinear') {\n const topInd = Math.floor(yInd);\n const bottomInd = Math.ceil(yInd);\n const yLerp = yInd - topInd;\n\n for (let x = 0; x < cropWidth; x++) {\n const xInd = (cropWidth > 1) ?\n x1 * (imageWidth - 1) + x * widthScale :\n 0.5 * (x1 + x2) * (imageWidth - 1);\n\n if (xInd < 0 || xInd > imageWidth - 1) {\n for (let c = 0; c < numChannels; c++) {\n const ind =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = extrapolationValue;\n }\n continue;\n }\n\n const leftInd = Math.floor(xInd);\n const rightInd = Math.ceil(xInd);\n const xLerp = xInd - leftInd;\n\n for (let c = 0; c < numChannels; c++) {\n let ind = c + leftInd * inStride[2] + topInd * inStride[1] +\n bInd * inStride[0];\n const topLeft = imageVals[ind];\n\n ind = c + rightInd * inStride[2] + topInd * inStride[1] +\n bInd * inStride[0];\n const topRight = imageVals[ind];\n\n ind = c + leftInd * inStride[2] + bottomInd * inStride[1] +\n bInd * inStride[0];\n const bottomLeft = imageVals[ind];\n\n ind = c + rightInd * inStride[2] + bottomInd * inStride[1] +\n bInd * inStride[0];\n const bottomRight = imageVals[ind];\n\n const top = topLeft + (topRight - topLeft) * xLerp;\n const bottom = bottomLeft + (bottomRight - bottomLeft) * xLerp;\n\n ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = top + ((bottom - top) * yLerp);\n }\n }\n } else { // method == \"nearest\"\n for (let x = 0; x < cropWidth; ++x) {\n const xInd = (cropWidth > 1) ?\n x1 * (imageWidth - 1) + x * widthScale :\n 0.5 * (x1 + x2) * (imageWidth - 1);\n\n if (xInd < 0 || xInd > imageWidth - 1) {\n for (let c = 0; c < numChannels; c++) {\n const ind =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = extrapolationValue;\n }\n continue;\n }\n\n const closestX = Math.round(xInd);\n const closestY = Math.round(yInd);\n for (let c = 0; c < numChannels; c++) {\n const inInd = c + closestX * inStride[2] + closestY * inStride[1] +\n bInd * inStride[0];\n const outInd =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[outInd] = imageVals[inInd];\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(output.shape, output.dtype, output.values);\n}\n\nexport const cropAndResizeConfig: KernelConfig = {\n kernelName: CropAndResize,\n backendName: 'cpu',\n kernelFunc: cropAndResize as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Cumprod, CumprodAttrs, CumprodInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function cumprod(\n args: {inputs: CumprodInputs, backend: MathBackendCPU,\n attrs: CumprodAttrs}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n\n assertNotComplex(x, 'cumprod');\n\n const permutation = backend_util.getAxesPermutation([axis], x.shape.length);\n let $x = x;\n if (permutation != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n }\n const permutedAxis = backend_util.getInnerMostAxes(1, x.shape.length)[0];\n\n if (permutedAxis !== $x.shape.length - 1) {\n throw new Error(\n `backend.cumprod in CPU expects an inner-most ` +\n `axis=${$x.shape.length - 1} but got axis=${permutedAxis}`);\n }\n\n const resultDtype = upcastType($x.dtype, 'int32');\n const vals = util.makeOnesTypedArray(\n util.sizeFromShape($x.shape), resultDtype) as TypedArray;\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n const finalDim = $x.shape[$x.shape.length - 1];\n const indexAdjuster = reverse ?\n (i: number, j: number) => i + finalDim - j - 1 :\n (i: number, j: number) => i + j;\n for (let i = 0; i < aVals.length; i += finalDim) {\n for (let j = 0; j < finalDim; j++) {\n const idx = indexAdjuster(i, j);\n if (j === 0) {\n vals[idx] = exclusive ? 1 : aVals[idx];\n } else {\n const prevIdx = indexAdjuster(i, j - 1);\n vals[idx] = exclusive ? aVals[prevIdx] * vals[prevIdx] :\n aVals[idx] * vals[prevIdx];\n }\n }\n }\n\n const result = backend.makeTensorInfo($x.shape, resultDtype, vals);\n\n if (permutation != null) {\n const reversePermutation = backend_util.getUndoAxesPermutation(permutation);\n const reverseTransposedResult = transpose(\n {inputs: {x: result}, backend, attrs: {perm: reversePermutation}});\n\n backend.disposeIntermediateTensorInfo(result);\n backend.disposeIntermediateTensorInfo($x);\n\n return reverseTransposedResult;\n }\n\n return result;\n}\n\nexport const cumprodConfig: KernelConfig = {\n kernelName: Cumprod,\n backendName: 'cpu',\n kernelFunc: cumprod as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Cumsum, CumsumAttrs, CumsumInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function cumsum(\n args: {inputs: CumsumInputs, backend: MathBackendCPU, attrs: CumsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n\n assertNotComplex(x, 'cumsum');\n\n const permutation = backend_util.getAxesPermutation([axis], x.shape.length);\n let $x = x;\n if (permutation != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n }\n const permutedAxis = backend_util.getInnerMostAxes(1, x.shape.length)[0];\n\n if (permutedAxis !== $x.shape.length - 1) {\n throw new Error(\n `backend.cumsum in CPU expects an inner-most ` +\n `axis=${$x.shape.length - 1} but got axis=${permutedAxis}`);\n }\n\n const resultDtype = upcastType($x.dtype, 'int32');\n const vals = util.makeZerosTypedArray(\n util.sizeFromShape($x.shape), resultDtype) as TypedArray;\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n const finalDim = $x.shape[$x.shape.length - 1];\n const indexAdjuster = reverse ?\n (i: number, j: number) => i + finalDim - j - 1 :\n (i: number, j: number) => i + j;\n for (let i = 0; i < aVals.length; i += finalDim) {\n for (let j = 0; j < finalDim; j++) {\n const idx = indexAdjuster(i, j);\n if (j === 0) {\n vals[idx] = exclusive ? 0 : aVals[idx];\n } else {\n const prevIdx = indexAdjuster(i, j - 1);\n vals[idx] = exclusive ? aVals[prevIdx] + vals[prevIdx] :\n aVals[idx] + vals[prevIdx];\n }\n }\n }\n\n const result = backend.makeTensorInfo($x.shape, resultDtype, vals);\n\n if (permutation != null) {\n const reversePermutation = backend_util.getUndoAxesPermutation(permutation);\n const reverseTransposedResult = transpose(\n {inputs: {x: result}, backend, attrs: {perm: reversePermutation}});\n\n backend.disposeIntermediateTensorInfo(result);\n backend.disposeIntermediateTensorInfo($x);\n\n return reverseTransposedResult;\n }\n\n return result;\n}\n\nexport const cumsumConfig: KernelConfig = {\n kernelName: Cumsum,\n backendName: 'cpu',\n kernelFunc: cumsum as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs, KernelConfig, KernelFunc, Rank, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {bincountImpl, bincountReduceImpl} from './Bincount_impl';\n\nexport function denseBincount(args: {\n inputs: DenseBincountInputs,\n backend: MathBackendCPU,\n attrs: DenseBincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size, binaryOutput} = attrs;\n\n if (x.shape.length === 1) {\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const weightsVals = backend.data.get(weights.dataId).values as TypedArray;\n\n const outVals =\n bincountImpl(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n } else if (x.shape.length === 2) {\n const xBuf = backend.bufferSync(x);\n const weightsBuf = backend.bufferSync(weights);\n\n const outBuf = bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput);\n\n return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);\n }\n\n throw new Error(\n `Error in denseBincount: input must be at most rank 2, but got rank` +\n `${x.shape.length}.`);\n}\n\nexport const denseBincountConfig: KernelConfig = {\n kernelName: DenseBincount,\n backendName: 'cpu',\n kernelFunc: denseBincount as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function depthToSpace(args: {\n inputs: DepthToSpaceInputs,\n backend: MathBackendCPU,\n attrs: DepthToSpaceAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockSize, dataFormat} = attrs;\n\n util.assert(\n dataFormat === 'NHWC',\n () => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${\n dataFormat}`);\n\n const batchSize = x.shape[0];\n const inputHeight = x.shape[1];\n const inputWidth = x.shape[2];\n const inputDepth = x.shape[3];\n\n const outputHeight = inputHeight * blockSize;\n const outputWidth = inputWidth * blockSize;\n const outputDepth = inputDepth / (blockSize * blockSize);\n\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const result =\n new Float32Array(batchSize * outputHeight * outputWidth * outputDepth);\n\n let outputIdx = 0;\n for (let b = 0; b < batchSize; ++b) {\n for (let h = 0; h < outputHeight; ++h) {\n const inH = Math.floor(h / blockSize);\n const offsetH = (h % blockSize);\n for (let w = 0; w < outputWidth; ++w) {\n const inW = Math.floor(w / blockSize);\n const offsetW = (w % blockSize);\n const offsetD = (offsetH * blockSize + offsetW) * outputDepth;\n for (let d = 0; d < outputDepth; ++d) {\n const inD = d + offsetD;\n const inputIdx =\n inD + inputDepth * (inW + inputWidth * (inH + inputHeight * b));\n result[outputIdx++] = xValues[inputIdx];\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batchSize, outputHeight, outputWidth, outputDepth], x.dtype, result);\n}\n\nexport const depthToSpaceConfig: KernelConfig = {\n kernelName: DepthToSpace,\n backendName: 'cpu',\n kernelFunc: depthToSpace as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function depthwiseConv2dNative(args: {\n inputs: DepthwiseConv2dNativeInputs,\n backend: MathBackendCPU,\n attrs: DepthwiseConv2dNativeAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations, dimRoundingMode} = attrs;\n\n assertNotComplex([x, filter], 'depthwiseConv2DNative');\n\n const xStrides = util.computeStrides(x.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n const {filterHeight, filterWidth, dilationHeight, dilationWidth, padInfo} =\n convInfo;\n const padLeft = padInfo.left;\n const padTop = padInfo.top;\n const chMul = convInfo.outChannels / convInfo.inChannels;\n const y = new TensorBuffer(convInfo.outShape, x.dtype as 'float32');\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const wVals = backend.data.get(filter.dataId).values as TypedArray;\n const yVals = y.values;\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xStrides[0];\n const yOffset1 = b * y.strides[0];\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const yOffset2 = yOffset1 + yR * y.strides[1];\n const xRCorner = yR * convInfo.strideHeight - padTop;\n for (let wR = 0; wR < filterHeight; ++wR) {\n const xR = xRCorner + wR * dilationHeight;\n if (xR < 0 || xR >= convInfo.inHeight) {\n continue;\n }\n const wOffset1 = wR * filterStrides[0];\n const xOffset2 = xOffset1 + xR * xStrides[1];\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const yOffset3 = yOffset2 + yC * y.strides[2];\n const xCCorner = yC * convInfo.strideWidth - padLeft;\n for (let wC = 0; wC < filterWidth; ++wC) {\n const xC = xCCorner + wC * dilationWidth;\n if (xC < 0 || xC >= convInfo.inWidth) {\n continue;\n }\n const wOffset2 = wOffset1 + wC * filterStrides[1];\n const xOffset3 = xOffset2 + xC * convInfo.inChannels;\n let yOffset4 = yOffset3;\n let wOffset3 = wOffset2;\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const xVal = xVals[xOffset3 + d1];\n for (let q = 0; q < chMul; ++q) {\n yVals[yOffset4 + q] += xVal * wVals[wOffset3 + q];\n }\n yOffset4 += chMul;\n wOffset3 += chMul;\n }\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(y.shape, y.dtype, y.values);\n}\n\nexport const depthwiseConv2dNativeConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNative,\n backendName: 'cpu',\n kernelFunc: depthwiseConv2dNative as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function depthwiseConv2dNativeBackpropFilter(args: {\n inputs: DepthwiseConv2dNativeBackpropFilterInputs,\n backend: MathBackendCPU,\n attrs: DepthwiseConv2dNativeBackpropFilterAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, dilations, pad, dimRoundingMode, filterShape} = attrs;\n\n assertNotComplex([x, dy], 'depthwiseConv2dNativeBackpropFilter');\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const {strideHeight, strideWidth, filterHeight, filterWidth} = convInfo;\n\n const dW = new TensorBuffer(convInfo.filterShape, 'float32');\n\n const leftPad = convInfo.padInfo.left;\n const topPad = convInfo.padInfo.top;\n const chMul = convInfo.outChannels / convInfo.inChannels;\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const xBuf = new TensorBuffer(x.shape, x.dtype, xVals);\n const dyVals = backend.data.get(dy.dataId).values as TypedArray;\n const dyBuf = new TensorBuffer(dy.shape, dy.dtype, dyVals);\n for (let wR = 0; wR < filterHeight; ++wR) {\n const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));\n const yRMax = Math.min(\n convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);\n\n for (let wC = 0; wC < filterWidth; ++wC) {\n const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));\n const yCMax = Math.min(\n convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);\n\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n const d1 = Math.trunc(d2 / chMul);\n const dm = d2 % chMul;\n\n let dotProd = 0;\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let yR = yRMin; yR < yRMax; ++yR) {\n const xR = wR + yR * strideHeight - topPad;\n for (let yC = yCMin; yC < yCMax; ++yC) {\n const xC = wC + yC * strideWidth - leftPad;\n dotProd += (xBuf.get(b, xR, xC, d1) as number) *\n (dyBuf.get(b, yR, yC, d2) as number);\n }\n }\n }\n dW.set(dotProd, wR, wC, d1, dm);\n }\n }\n }\n\n return backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);\n}\n\nexport const depthwiseConv2dNativeBackpropFilterConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropFilter,\n backendName: 'cpu',\n kernelFunc: depthwiseConv2dNativeBackpropFilter as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function depthwiseConv2dNativeBackpropInput(args: {\n inputs: DepthwiseConv2dNativeBackpropInputInputs,\n backend: MathBackendCPU,\n attrs: DepthwiseConv2dNativeBackpropInputAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {strides, dilations, pad, dimRoundingMode, inputShape} = attrs;\n\n assertNotComplex([dy, filter], 'depthwiseConv2DNativeBackpropInput');\n\n const dyStrides = util.computeStrides(dy.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const dx = new TensorBuffer(convInfo.inShape, 'float32');\n const dxValues = dx.values;\n const [dxS0, dxS1, dxS2] = dx.strides;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const [dyS0, dyS1, dyS2] = dyStrides;\n const fltValues = backend.data.get(filter.dataId).values as TypedArray;\n const [fltS0, fltS1, fltS2] = filterStrides;\n const {\n batchSize,\n filterHeight,\n filterWidth,\n inChannels,\n inHeight,\n inWidth,\n outChannels,\n outHeight,\n outWidth,\n strideHeight,\n strideWidth\n } = convInfo;\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n const chMul = outChannels / inChannels;\n\n for (let b = 0; b < batchSize; ++b) {\n for (let d1 = 0; d1 < inChannels; ++d1) {\n for (let xR = 0; xR < inHeight; ++xR) {\n const xRCorner = xR - topPad;\n const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));\n const yRMax =\n Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);\n\n for (let xC = 0; xC < inWidth; ++xC) {\n const xCCorner = xC - leftPad;\n const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));\n const yCMax =\n Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);\n\n let dotProd = 0;\n for (let yR = xRMin; yR < yRMax; ++yR) {\n const wR = yR * strideHeight - xRCorner;\n\n for (let yC = xCMin; yC < yCMax; ++yC) {\n const wC = yC * strideWidth - xCCorner;\n const dyOffset = dyS0 * b + dyS1 * yR + dyS2 * yC;\n const fltOffset = fltS0 * (filterHeight - 1 - wR) +\n fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;\n\n for (let dm = 0; dm < chMul; ++dm) {\n const d2 = d1 * chMul + dm;\n const pixel = dyValues[dyOffset + d2];\n const weight = fltValues[fltOffset + dm];\n dotProd += pixel * weight;\n }\n }\n }\n dxValues[dxS0 * b + dxS1 * xR + dxS2 * xC + d1] = dotProd;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const depthwiseConv2dNativeBackpropInputConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropInput,\n backendName: 'cpu',\n kernelFunc: depthwiseConv2dNativeBackpropInput as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, Diag, DiagInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function diag(args: {inputs: DiagInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const xSize = util.sizeFromShape(x.shape);\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const outBuf = buffer([xSize, xSize], x.dtype);\n const vals = outBuf.values;\n for (let i = 0; i < xVals.length; i++) {\n vals[i * xSize + i] = xVals[i];\n }\n\n const outShape = [...x.shape, ...x.shape];\n\n return backend.makeTensorInfo(outShape, outBuf.dtype, outBuf.values);\n}\n\nexport const diagConfig: KernelConfig = {\n kernelName: Diag,\n backendName: 'cpu',\n kernelFunc: diag as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Dilation2D, Dilation2DAttrs, Dilation2DInputs, KernelConfig, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const dilation2DConfig: KernelConfig = {\n kernelName: Dilation2D,\n backendName: 'cpu',\n kernelFunc: ({inputs, backend, attrs}) => {\n const {x, filter} = inputs as Dilation2DInputs;\n const {strides, pad, dilations} = attrs as unknown as Dilation2DAttrs;\n const cpuBackend = backend as MathBackendCPU;\n\n const xVals = cpuBackend.data.get(x.dataId).values as TypedArray;\n const xRank = x.shape.length;\n\n const filterVals = cpuBackend.data.get(filter.dataId).values as TypedArray;\n const filterRank = filter.shape.length;\n\n const {\n batchSize,\n inHeight,\n inWidth,\n inChannels,\n outHeight,\n outWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth,\n outShape\n } =\n backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n\n const outSize = util.sizeFromShape(outShape);\n const outRank = outShape.length;\n const outputVals = util.getArrayFromDType(x.dtype, outSize);\n\n // Upsampling the input by fill in `dilation size - 1` values between each\n // input value.\n // This implementation follows the TF c++ implementation:\n // https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc\n for (let b = 0; b < batchSize; ++b) {\n for (let hOut = 0; hOut < outHeight; ++hOut) {\n const hBeg = hOut * strideHeight - padInfo.top;\n for (let wOut = 0; wOut < outWidth; ++wOut) {\n const wBeg = wOut * strideWidth - padInfo.left;\n for (let d = 0; d < inChannels; ++d) {\n let curVal = Number.MIN_SAFE_INTEGER;\n for (let h = 0; h < filterHeight; ++h) {\n const hIn = hBeg + h * dilationHeight;\n if (hIn >= 0 && hIn < inHeight) {\n for (let w = 0; w < filterWidth; ++w) {\n const wIn = wBeg + w * dilationWidth;\n if (wIn >= 0 && wIn < inWidth) {\n const xIndex = util.locToIndex(\n [b, hIn, wIn, d], xRank, util.computeStrides(x.shape));\n const filterIndex = util.locToIndex(\n [h, w, d], filterRank,\n util.computeStrides(filter.shape));\n const val = xVals[xIndex] + filterVals[filterIndex];\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n const outputIndex = util.locToIndex(\n [b, hOut, wOut, d], outRank, util.computeStrides(outShape));\n outputVals[outputIndex] = curVal;\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(\n util.toTypedArray(outputVals, x.dtype), outShape, x.dtype);\n\n return {dataId, shape: outShape, dtype: x.dtype};\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Dilation2DAttrs, Dilation2DBackpropFilter, Tensor3D, Tensor4D, TypedArray, util} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const dilation2DBackpropFilterConfig: KernelConfig = {\n kernelName: Dilation2DBackpropFilter,\n backendName: 'cpu',\n kernelFunc: ({inputs, backend, attrs}) => {\n const {x, filter, dy} =\n inputs as {x: Tensor4D, filter: Tensor3D, dy: Tensor4D};\n const {strides, pad, dilations} = attrs as unknown 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 unknown 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 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Draw, DrawAttrs, DrawInputs, KernelConfig, KernelFunc, TypedArray} from '@tensorflow/tfjs-core';\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function draw(\n args: {inputs: DrawInputs, backend: MathBackendCPU, attrs: DrawAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image} = inputs;\n const {canvas, options} = attrs;\n const {contextOptions, imageOptions} = options || {};\n const alpha = imageOptions ?.alpha || 1;\n\n const contextType = contextOptions ?.contextType || '2d';\n if (contextType !== '2d') {\n throw new Error(`Context type ${\n contextOptions.contextType} is not supported by the CPU backend.`);\n }\n const ctx = canvas.getContext(contextType,\n contextOptions?.contextAttributes || {}) as CanvasRenderingContext2D ;\n if (ctx == null) {\n throw new Error(`Could not get the context with ${contextType} type.`);\n }\n\n const [height, width] = image.shape.slice(0, 2);\n const depth = image.shape.length === 2 ? 1 : image.shape[2];\n const data = backend.data.get(image.dataId).values as TypedArray;\n const multiplier = image.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 * alpha];\n\n for (let d = 0; d < depth; d++) {\n const value = data[i * depth + d];\n\n if (image.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 (image.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 canvas.width = width;\n canvas.height = height;\n const imageData = new ImageData(bytes, width, height);\n ctx.putImageData(imageData, 0, 0);\n return image;\n}\n\nexport const drawConfig: KernelConfig = {\n kernelName: Draw,\n backendName: 'cpu',\n kernelFunc: draw as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Sum, SumAttrs, SumInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {zeros} from '../utils/zeros_impl';\nimport {cast} from './Cast';\nimport {identity} from './Identity';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function sum(\n args: {inputs: SumInputs, backend: MathBackendCPU, attrs: SumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'sum');\n\n let $x;\n if (x.dtype === 'bool') {\n $x = cast({inputs: {x}, backend, attrs: {dtype: 'int32'}});\n } else {\n $x = identity({inputs: {x}, backend});\n }\n\n const xRank = $x.shape.length;\n const axes = util.parseAxisParam(axis, $x.shape);\n const permutation = backend_util.getAxesPermutation(axes, xRank);\n\n let reductionAxes = axes;\n let permutedX = $x;\n if (permutation != null) {\n permutedX =\n transpose({inputs: {x: $x}, backend, attrs: {perm: permutation}});\n reductionAxes = backend_util.getInnerMostAxes(reductionAxes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims(\n 'sum', reductionAxes, permutedX.shape.length);\n\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, reductionAxes);\n const resultDtype = backend_util.upcastType(permutedX.dtype, 'int32');\n let result = zeros(backend, outShape, resultDtype);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = backend.data.get(result.dataId).values as TypedArray;\n\n const aVals = backend.data.get(permutedX.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let sum = 0;\n for (let j = 0; j < reduceSize; ++j) {\n sum += aVals[offset + j];\n }\n vals[i] = sum;\n }\n\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(result.shape, axes);\n const oldResult = result;\n result = reshape({inputs: {x: result}, backend, attrs: {shape: newShape}});\n backend.disposeIntermediateTensorInfo(oldResult);\n }\n\n backend.disposeIntermediateTensorInfo($x);\n\n if (permutation != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return result;\n}\n\nexport const sumConfig: KernelConfig = {\n kernelName: Sum,\n backendName: 'cpu',\n kernelFunc: sum as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Einsum, EinsumAttrs, EinsumInputs, KernelConfig, KernelFunc, Tensor, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {multiply} from './Multiply';\nimport {reshape} from './Reshape';\nimport {sum} from './Sum';\nimport {transpose} from './Transpose';\n\nexport function einsum(\n args: {inputs: EinsumInputs, backend: MathBackendCPU, attrs: EinsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {equation} = attrs;\n const tensors = inputs as Tensor[];\n\n const {allDims, summedDims, idDims} =\n backend_util.decodeEinsumEquation(equation, tensors.length);\n backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);\n const {path, steps} = backend_util.getEinsumComputePath(summedDims, idDims);\n\n const nSteps = steps.length;\n let out: TensorInfo|null = null;\n let numDimsRemaining = allDims.length;\n const tensorsToDispose: TensorInfo[] = [];\n for (let i = 0; i < nSteps; ++i) {\n for (const idTerm of steps[i]) {\n const {permutationIndices: perm, expandDims: dimsToExpand} =\n backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]);\n let x: TensorInfo;\n if (backend_util.isIdentityPermutation(perm)) {\n x = tensors[idTerm];\n } else {\n x = transpose({inputs: {x: tensors[idTerm]}, backend, attrs: {perm}});\n tensorsToDispose.push(x);\n }\n const targetShape: number[] = x.shape.slice();\n for (let k = 0; k < dimsToExpand.length; ++k) {\n targetShape.splice(dimsToExpand[k], 0, 1);\n }\n\n if (!util.arraysEqual(x.shape, targetShape)) {\n x = reshape({inputs: {x}, backend, attrs: {shape: targetShape}});\n tensorsToDispose.push(x);\n }\n if (out === null) {\n out = x;\n } else {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n out = multiply({inputs: {a: x, b: out}, backend}) as TensorInfo;\n tensorsToDispose.push(out);\n }\n }\n if (i < nSteps - 1) {\n if (path[i] >= 0) {\n out = sum({\n inputs: {x: out},\n backend,\n attrs: {\n axis: path[i] - (allDims.length - numDimsRemaining),\n keepDims: false\n }\n });\n tensorsToDispose.push(out);\n }\n numDimsRemaining--;\n }\n }\n\n // Clean up intermediate tensors.\n for (const tensorInfo of tensorsToDispose) {\n if (tensorInfo === out) {\n continue;\n }\n backend.disposeIntermediateTensorInfo(tensorInfo);\n }\n\n return out;\n}\n\nexport const einsumConfig: KernelConfig = {\n kernelName: Einsum,\n backendName: 'cpu',\n kernelFunc: einsum as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {EluGrad, EluGradInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function eluGrad(args: {inputs: EluGradInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {dy, y} = inputs;\n\n assertNotComplex([dy, y], 'eluGrad');\n\n const resultValues = new Float32Array(util.sizeFromShape(y.shape));\n const values = backend.data.get(y.dataId).values as TypedArray;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n for (let i = 0; i < values.length; ++i) {\n const v = values[i];\n if (v >= 0) {\n resultValues[i] = dyValues[i];\n } else {\n resultValues[i] = dyValues[i] * (v + 1);\n }\n }\n\n return backend.makeTensorInfo(y.shape, 'float32', resultValues);\n}\n\nexport const eluGradConfig: KernelConfig = {\n kernelName: EluGrad,\n backendName: 'cpu',\n kernelFunc: eluGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Erf, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nconst p = backend_util.ERF_P;\nconst a1 = backend_util.ERF_A1;\nconst a2 = backend_util.ERF_A2;\nconst a3 = backend_util.ERF_A3;\nconst a4 = backend_util.ERF_A4;\nconst a5 = backend_util.ERF_A5;\n\nexport const erf = unaryKernelFunc(\n Erf,\n (xi) => {\n const sign = Math.sign(xi);\n const v = Math.abs(xi);\n const t = 1.0 / (1.0 + p * v);\n return sign *\n (1.0 -\n (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t *\n Math.exp(-v * v));\n },\n);\n\nexport const erfConfig: KernelConfig = {\n kernelName: Erf,\n backendName: 'cpu',\n kernelFunc: erf,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {reshape} from './Reshape';\n\nexport function expandDims(args: {\n inputs: ExpandDimsInputs,\n backend: MathBackendCPU,\n attrs: ExpandDimsAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {input} = inputs;\n const {dim} = attrs;\n\n const inputRank = input.shape.length;\n const newShape = input.shape.slice();\n let $dim = dim;\n if (dim < 0) {\n // Negative value is counted from the tail of rank.\n util.assert(\n -(inputRank + 1) <= dim,\n () => `Axis must be in the interval [${- (inputRank + 1)}, ${\n inputRank}]`);\n $dim = inputRank + dim + 1;\n }\n newShape.splice($dim, 0, 1);\n\n return reshape({inputs: {x: input}, backend, attrs: {shape: newShape}});\n}\n\nexport const expandDimsConfig: KernelConfig = {\n kernelName: ExpandDims,\n backendName: 'cpu',\n kernelFunc: expandDims as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, RealDiv} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const realDivImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => a / b);\nexport const div = binaryKernelFunc(RealDiv, realDivImpl);\n\nexport const realDivConfig: KernelConfig = {\n kernelName: RealDiv,\n backendName: 'cpu',\n kernelFunc: div\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Tensor, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {add} from '../kernels/Add';\nimport {complex} from '../kernels/Complex';\nimport {concat} from '../kernels/Concat';\nimport {identity} from '../kernels/Identity';\nimport {imag} from '../kernels/Imag';\nimport {multiply} from '../kernels/Multiply';\nimport {real} from '../kernels/Real';\nimport {realDivConfig} from '../kernels/RealDiv';\nimport {slice} from '../kernels/Slice';\nimport {sub} from '../kernels/Sub';\n\n/**\n * Calculate FFT of inner most elements of batch tensor.\n */\nexport function fftBatch(\n input: TensorInfo, inverse: boolean,\n cpuBackend: MathBackendCPU): TensorInfo {\n const inputShape = input.shape;\n const batch = inputShape[0];\n const innerDim = inputShape[1];\n\n const inputVals = cpuBackend.data.get(input.dataId);\n\n const real2D = inputVals.complexTensorInfos.real;\n const imag2D = inputVals.complexTensorInfos.imag;\n\n // Collects real and imaginary values separately.\n const resultShape = [batch, innerDim];\n const resultSize = util.sizeFromShape(resultShape);\n const resultReal = util.getTypedArrayFromDType('float32', resultSize);\n const resultImag = util.getTypedArrayFromDType('float32', resultSize);\n\n for (let b = 0; b < batch; b++) {\n // TODO: Support slice ops for complex type.\n const r = slice({\n inputs: {x: real2D},\n backend: cpuBackend,\n attrs: {begin: [b, 0], size: [1, innerDim]}\n });\n const i = slice({\n inputs: {x: imag2D},\n backend: cpuBackend,\n attrs: {begin: [b, 0], size: [1, innerDim]}\n });\n\n const input = complex({inputs: {real: r, imag: i}, backend: cpuBackend});\n\n // Run FFT by batch element.\n const {real, imag} = fftImpl(input, inverse, cpuBackend);\n const res = backend_util.mergeRealAndImagArrays(real, imag);\n\n for (let d = 0; d < innerDim; d++) {\n const c = backend_util.getComplexWithIndex(res, d);\n resultReal[b * innerDim + d] = c.real;\n resultImag[b * innerDim + d] = c.imag;\n }\n\n cpuBackend.disposeIntermediateTensorInfo(r);\n cpuBackend.disposeIntermediateTensorInfo(i);\n cpuBackend.disposeIntermediateTensorInfo(input);\n }\n\n const $realInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', resultReal);\n const $imagInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', resultImag);\n\n const result = complex(\n {inputs: {real: $realInfo, imag: $imagInfo}, backend: cpuBackend});\n\n cpuBackend.disposeIntermediateTensorInfo($realInfo);\n cpuBackend.disposeIntermediateTensorInfo($imagInfo);\n\n return result;\n}\n\nexport function fftImpl(\n input: TensorInfo, inverse: boolean,\n cpuBackend: MathBackendCPU): {real: Float32Array, imag: Float32Array} {\n const inputSize = util.sizeFromShape(input.shape);\n\n const inputVals = cpuBackend.data.get(input.dataId);\n\n const realVals =\n cpuBackend.data.get(inputVals.complexTensorInfos.real.dataId).values as\n Float32Array;\n\n const imagVals =\n cpuBackend.data.get(inputVals.complexTensorInfos.imag.dataId).values as\n Float32Array;\n\n if (isExponentOf2(inputSize)) {\n const result =\n fftRadix2(realVals, imagVals, inputSize, inverse, cpuBackend);\n\n const resultShape = [input.shape[0], input.shape[1]];\n\n if (inverse) {\n const realInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', result.real);\n const imagInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', result.imag);\n\n const sizeInfo: TensorInfo = cpuBackend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(inputSize as unknown as 'float32', 'float32'));\n const sizeInfoCopy =\n identity({inputs: {x: sizeInfo}, backend: cpuBackend});\n\n const divRealInfo =\n realDivConfig.kernelFunc(\n {inputs: {a: realInfo, b: sizeInfo}, backend: cpuBackend}) as\n TensorInfo;\n const divImagInfo =\n realDivConfig.kernelFunc(\n {inputs: {a: imagInfo, b: sizeInfoCopy}, backend: cpuBackend}) as\n TensorInfo;\n\n const divRealVals =\n cpuBackend.data.get(divRealInfo.dataId).values as Float32Array;\n const divImagVals =\n cpuBackend.data.get(divImagInfo.dataId).values as Float32Array;\n\n cpuBackend.disposeIntermediateTensorInfo(realInfo);\n cpuBackend.disposeIntermediateTensorInfo(imagInfo);\n cpuBackend.disposeIntermediateTensorInfo(sizeInfo);\n cpuBackend.disposeIntermediateTensorInfo(sizeInfoCopy);\n cpuBackend.disposeIntermediateTensorInfo(divRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(divImagInfo);\n\n return {real: divRealVals, imag: divImagVals};\n }\n\n return result;\n } else {\n const data = backend_util.mergeRealAndImagArrays(realVals, imagVals);\n\n const rawOutput =\n fourierTransformByMatmul(data, inputSize, inverse) as Float32Array;\n\n return backend_util.splitRealAndImagArrays(rawOutput);\n }\n}\n\nfunction isExponentOf2(size: number): boolean {\n return (size & size - 1) === 0;\n}\n\n// FFT using Cooley-Tukey algorithm on radix 2 dimensional input.\nfunction fftRadix2(\n realVals: Float32Array, imagVals: Float32Array, size: number,\n inverse: boolean,\n cpuBackend: MathBackendCPU): {real: Float32Array, imag: Float32Array} {\n if (size === 1) {\n return {real: realVals, imag: imagVals};\n }\n\n const data = backend_util.mergeRealAndImagArrays(realVals, imagVals);\n\n const half = size / 2;\n\n const evenComplex = backend_util.complexWithEvenIndex(data);\n\n const evenRealVals = evenComplex.real;\n const evenImagVals = evenComplex.imag;\n\n const evenShape = [evenRealVals.length];\n\n const evenRealInfo =\n cpuBackend.makeTensorInfo(evenShape, 'float32', evenRealVals);\n const evenImagInfo =\n cpuBackend.makeTensorInfo(evenShape, 'float32', evenImagVals);\n\n const evenTensorInfo = complex(\n {inputs: {real: evenRealInfo, imag: evenImagInfo}, backend: cpuBackend});\n\n const oddComplex = backend_util.complexWithOddIndex(data);\n\n const oddRealVals = oddComplex.real;\n const oddImagVals = oddComplex.imag;\n\n const oddShape = [oddRealVals.length];\n\n const oddRealInfo =\n cpuBackend.makeTensorInfo(oddShape, 'float32', oddRealVals);\n const oddImagInfo =\n cpuBackend.makeTensorInfo(oddShape, 'float32', oddImagVals);\n\n const oddTensorInfo = complex(\n {inputs: {real: oddRealInfo, imag: oddImagInfo}, backend: cpuBackend});\n\n // Recursive call for half part of original input.\n const $evenComplex =\n fftRadix2(evenRealVals, evenImagVals, half, inverse, cpuBackend);\n\n const $evenRealVals = $evenComplex.real;\n const $evenImagVals = $evenComplex.imag;\n\n const $evenShape = [$evenRealVals.length];\n\n const $evenRealInfo =\n cpuBackend.makeTensorInfo($evenShape, 'float32', $evenRealVals);\n const $evenImagInfo =\n cpuBackend.makeTensorInfo($evenShape, 'float32', $evenImagVals);\n\n const $evenTensorInfo = complex({\n inputs: {real: $evenRealInfo, imag: $evenImagInfo},\n backend: cpuBackend\n });\n\n const $oddComplex =\n fftRadix2(oddRealVals, oddImagVals, half, inverse, cpuBackend);\n\n const $oddRealVals = $oddComplex.real;\n const $oddImagVals = $oddComplex.imag;\n\n const $oddShape = [$oddRealVals.length];\n\n const $oddRealInfo =\n cpuBackend.makeTensorInfo($oddShape, 'float32', $oddRealVals);\n const $oddImagInfo =\n cpuBackend.makeTensorInfo($oddShape, 'float32', $oddImagVals);\n\n const $oddTensorInfo = complex(\n {inputs: {real: $oddRealInfo, imag: $oddImagInfo}, backend: cpuBackend});\n\n const e = backend_util.exponents(size, inverse);\n const eShape = [e.real.length];\n\n const eRealInfo = cpuBackend.makeTensorInfo(eShape, 'float32', e.real);\n const eImagInfo = cpuBackend.makeTensorInfo(eShape, 'float32', e.imag);\n\n const complexInfo = complex(\n {inputs: {real: eRealInfo, imag: eImagInfo}, backend: cpuBackend});\n\n const exponentInfo =\n multiply(\n {inputs: {a: complexInfo, b: $oddTensorInfo}, backend: cpuBackend}) as\n TensorInfo;\n\n const addPart = add({\n inputs: {a: $evenTensorInfo, b: exponentInfo},\n backend: cpuBackend\n }) as TensorInfo;\n const subPart = sub({\n inputs: {a: $evenTensorInfo, b: exponentInfo},\n backend: cpuBackend\n }) as TensorInfo;\n\n const addPartReal = real({inputs: {input: addPart}, backend: cpuBackend});\n const subPartReal = real({inputs: {input: subPart}, backend: cpuBackend});\n\n const addPartImag = imag({inputs: {input: addPart}, backend: cpuBackend});\n const subPartImag = imag({inputs: {input: subPart}, backend: cpuBackend});\n\n const $real = concat({\n inputs: [addPartReal as Tensor, subPartReal as Tensor],\n backend: cpuBackend,\n attrs: {axis: 0}\n });\n const $imag = concat({\n inputs: [addPartImag as Tensor, subPartImag as Tensor],\n backend: cpuBackend,\n attrs: {axis: 0}\n });\n\n const $realVals = cpuBackend.data.get($real.dataId).values as Float32Array;\n const $imagVals = cpuBackend.data.get($imag.dataId).values as Float32Array;\n\n cpuBackend.disposeIntermediateTensorInfo(evenRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(evenImagInfo);\n cpuBackend.disposeIntermediateTensorInfo(evenTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo(oddRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(oddImagInfo);\n cpuBackend.disposeIntermediateTensorInfo(oddTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo($evenRealInfo);\n cpuBackend.disposeIntermediateTensorInfo($evenImagInfo);\n cpuBackend.disposeIntermediateTensorInfo($evenTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo($oddRealInfo);\n cpuBackend.disposeIntermediateTensorInfo($oddImagInfo);\n cpuBackend.disposeIntermediateTensorInfo($oddTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo(eRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(eImagInfo);\n cpuBackend.disposeIntermediateTensorInfo(complexInfo);\n cpuBackend.disposeIntermediateTensorInfo(exponentInfo);\n cpuBackend.disposeIntermediateTensorInfo(addPart);\n cpuBackend.disposeIntermediateTensorInfo(subPart);\n cpuBackend.disposeIntermediateTensorInfo(addPartReal);\n cpuBackend.disposeIntermediateTensorInfo(addPartImag);\n cpuBackend.disposeIntermediateTensorInfo(subPartReal);\n cpuBackend.disposeIntermediateTensorInfo(subPartImag);\n cpuBackend.disposeIntermediateTensorInfo($real);\n cpuBackend.disposeIntermediateTensorInfo($imag);\n\n return {real: $realVals, imag: $imagVals};\n}\n\n// Calculate fourier transform by multplying sinusoid matrix.\nfunction fourierTransformByMatmul(\n data: TypedArray, size: number, inverse: boolean): TypedArray {\n const ret = new Float32Array(size * 2);\n // TODO: Use matmul instead once it supports complex64 type.\n for (let r = 0; r < size; r++) {\n let real = 0.0;\n let imag = 0.0;\n for (let c = 0; c < size; c++) {\n const e = backend_util.exponent(r * c, size, inverse);\n const term = backend_util.getComplexWithIndex(data as Float32Array, c);\n real += term.real * e.real - term.imag * e.imag;\n imag += term.real * e.imag + term.imag * e.real;\n }\n if (inverse) {\n real /= size;\n imag /= size;\n }\n backend_util.assignToTypedArray(ret, real, imag, r);\n }\n return ret;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FFT, FFTInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {fftBatch} from '../utils/fft_utils';\nimport {reshape} from './Reshape';\n\nexport function fft(args: {inputs: FFTInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n const inputSize = util.sizeFromShape(input.shape);\n\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape({\n inputs: {x: input},\n backend,\n attrs: {shape: [batch, innerDimensionSize]}\n });\n\n const result = fftBatch(input2D, false, backend);\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: input.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const fftConfig: KernelConfig = {\n kernelName: FFT,\n backendName: 'cpu',\n kernelFunc: fft as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, DataValues, Fill, FillAttrs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function fill(args: {backend: MathBackendCPU, attrs: FillAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {shape, value, dtype} = attrs;\n\n const $dtype = dtype || util.inferDtype(value);\n const values = util.getArrayFromDType($dtype, util.sizeFromShape(shape));\n fillValues(values, value, $dtype);\n\n return backend.makeTensorInfo(shape, $dtype, values);\n}\n\nexport const fillConfig: KernelConfig = {\n kernelName: Fill,\n backendName: 'cpu',\n kernelFunc: fill as unknown as KernelFunc\n};\n\nfunction fillValues(\n values: DataValues, value: string|number, dtype: DataType): void {\n if (dtype === 'string') {\n (values as string[]).fill(value as string);\n } else {\n (values as TypedArray).fill(value as number);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, NumericDataType, TypedArray} from '@tensorflow/tfjs-core';\nimport {FlipLeftRight, FlipLeftRightInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const flipLeftRightConfig: KernelConfig = {\n kernelName: FlipLeftRight,\n backendName: 'cpu',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as FlipLeftRightInputs;\n const cpuBackend = backend as MathBackendCPU;\n\n const output = util.getTypedArrayFromDType(\n image.dtype as NumericDataType, util.sizeFromShape(image.shape));\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n\n const imageVals = cpuBackend.data.get(image.dataId).values as TypedArray;\n\n for (let batchIdx = 0; batchIdx < batch; batchIdx++) {\n const batchOffset = batchIdx * imageWidth * imageHeight * numChannels;\n\n for (let row = 0; row < imageHeight; row++) {\n const rowOffset = row * (imageWidth * numChannels);\n\n for (let col = 0; col < imageWidth; col++) {\n const colOffset = col * numChannels;\n\n for (let channel = 0; channel < numChannels; channel++) {\n const coordX = Math.round(imageWidth - col - 1);\n const outIdx = batchOffset + rowOffset + colOffset + channel;\n\n let outputValue = imageVals[outIdx];\n // If the coordinate position falls within the image boundaries...\n if (coordX >= 0 && coordX < imageWidth) {\n // set the output to the image value at the coordinate position.\n const rotatedColOffset = coordX * numChannels;\n const imageIdx =\n batchOffset + rowOffset + rotatedColOffset + channel;\n outputValue = imageVals[imageIdx];\n }\n output[outIdx] = outputValue;\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(output, image.shape, image.dtype);\n return {dataId, shape: image.shape, dtype: image.dtype};\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {applyActivation} from '../utils/fused_utils';\nimport {add} from './Add';\nimport {conv2D} from './Conv2D';\nimport {reshape} from './Reshape';\n\nexport function fusedConv2D(args: {\n inputs: FusedConv2DInputs,\n backend: MathBackendCPU,\n attrs: FusedConv2DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n let result = conv2D({\n inputs: {x, filter},\n backend,\n attrs: {strides, pad, dataFormat, dilations, dimRoundingMode}\n });\n\n if (bias) {\n const resultOld = result;\n // For NCHW format, if bias is a 1-D tensor, it is supposed to be aligned\n // to the channel of the conv2d's result; if the bias is a scalar, the\n // bias_add is computed as if the bias was broadcasted to the shape of the\n // conv2d's result.\n if (dataFormat === 'NCHW' && bias.shape.length === 1 &&\n bias.shape[0] !== 1) {\n const reshapedBias = reshape(\n {inputs: {x: bias}, backend, attrs: {shape: [bias.shape[0], 1, 1]}});\n result =\n add({inputs: {a: result, b: reshapedBias}, backend}) as TensorInfo;\n backend.disposeIntermediateTensorInfo(reshapedBias);\n } else {\n // This condition handles NHWC and NCHW (scalar case). The only other case\n // for NCHW (1D case) is handled above.\n result = add({inputs: {a: result, b: bias}, backend}) as TensorInfo;\n }\n backend.disposeIntermediateTensorInfo(resultOld);\n }\n\n if (activation) {\n const resultOld = result;\n // For NCHW format, if PReLu activation weights is a 1-D tensor, it is\n // supposed to be aligned with the channel of the conv2d's result. For other\n // cases, whether NCHW or NHWC data format, the conv2d result is\n // already aligned with the activation weights.\n if (dataFormat === 'NCHW' && activation === 'prelu' &&\n preluActivationWeights.shape.length === 1 &&\n preluActivationWeights.shape[0] !== 1) {\n const reshapedAlpha = reshape({\n inputs: {x: preluActivationWeights},\n backend,\n attrs: {shape: [preluActivationWeights.shape[0], 1, 1]}\n });\n result = applyActivation(\n backend, result, activation, reshapedAlpha, leakyreluAlpha);\n backend.disposeIntermediateTensorInfo(reshapedAlpha);\n } else {\n result = applyActivation(\n backend, result, activation, preluActivationWeights, leakyreluAlpha);\n }\n backend.disposeIntermediateTensorInfo(resultOld);\n }\n\n return result;\n}\n\nexport const fusedConv2DConfig: KernelConfig = {\n kernelName: FusedConv2D,\n backendName: 'cpu',\n kernelFunc: fusedConv2D as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {applyActivation} from '../utils/fused_utils';\nimport {add} from './Add';\nimport {depthwiseConv2dNative} from './DepthwiseConv2dNative';\n\nexport function fusedDepthwiseConv2D(args: {\n inputs: FusedDepthwiseConv2DInputs,\n backend: MathBackendCPU,\n attrs: FusedDepthwiseConv2DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n let result = depthwiseConv2dNative({\n inputs: {x, filter},\n backend,\n attrs: {strides, pad, dataFormat, dilations, dimRoundingMode}\n });\n\n if (bias) {\n const oldResult = result;\n result = add({inputs: {a: result, b: bias}, backend}) as TensorInfo;\n backend.disposeIntermediateTensorInfo(oldResult);\n }\n if (activation) {\n const oldResult = result;\n result = applyActivation(\n backend, result, activation, preluActivationWeights, leakyreluAlpha);\n backend.disposeIntermediateTensorInfo(oldResult);\n }\n\n return result;\n}\n\nexport const fusedDepthwiseConv2DConfig: KernelConfig = {\n kernelName: FusedDepthwiseConv2D,\n backendName: 'cpu',\n kernelFunc: fusedDepthwiseConv2D as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherNd, GatherNdInputs, KernelConfig, KernelFunc, Rank, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {gatherNdImpl} from './GatherNd_Impl';\n\nexport function gatherNd(\n args: {inputs: GatherNdInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {params, indices} = inputs;\n\n const paramsSize = util.sizeFromShape(params.shape);\n\n const indicesShape = indices.shape;\n const sliceRank = indicesShape[indicesShape.length - 1];\n\n const [resultShape, numSlices, sliceSize, strides] =\n backend_util.prepareAndValidate(params, indices);\n if (numSlices === 0) {\n return backend.makeTensorInfo(resultShape, params.dtype, []);\n }\n\n const indicesData = backend.data.get(indices.dataId).values as TypedArray;\n const paramsBuf = backend.bufferSync(params);\n const outBuf = gatherNdImpl(\n indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize,\n strides, params.shape, paramsSize);\n\n return backend.makeTensorInfo(resultShape, params.dtype, outBuf.values);\n}\n\nexport const gatherNdConfig: KernelConfig = {\n kernelName: GatherNd,\n backendName: 'cpu',\n kernelFunc: gatherNd as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherV2, GatherV2Attrs, GatherV2Inputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {gatherV2Impl} from './GatherV2_impl';\nimport {reshape} from './Reshape';\n\nexport function gatherV2(args: {\n inputs: GatherV2Inputs,\n backend: MathBackendCPU,\n attrs: GatherV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, indices} = inputs;\n const {axis, batchDims} = attrs;\n\n assertNotComplex([x, indices], 'gatherV2');\n\n // Throw error when any index is out of bound.\n const parsedAxis = util.parseAxisParam(axis, x.shape)[0];\n const indicesVals = backend.data.get(indices.dataId).values as TypedArray;\n const axisDim = x.shape[parsedAxis];\n for (let i = 0; i < indicesVals.length; ++i) {\n const index = indicesVals[i];\n util.assert(\n index <= axisDim - 1 && index >= 0,\n () =>\n `GatherV2: the index value ${index} is not in [0, ${axisDim - 1}]`);\n }\n\n let $batchDims = batchDims;\n\n if (batchDims == null) {\n $batchDims = 0;\n }\n\n const indicesSize = util.sizeFromShape(indices.shape);\n\n const shapeInfo = backend_util.segment_util.collectGatherOpShapeInfo(\n x, indices, parsedAxis, $batchDims);\n\n const flattenX = reshape({\n inputs: {x},\n backend,\n attrs: {\n shape: [\n shapeInfo.batchSize, shapeInfo.outerSize, shapeInfo.dimSize,\n shapeInfo.sliceSize\n ]\n }\n });\n\n const flattenIndex = reshape({\n inputs: {x: indices},\n backend,\n attrs: {shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize]}\n });\n\n const flattenOutputShape = [\n shapeInfo.batchSize, shapeInfo.outerSize, indicesSize / shapeInfo.batchSize,\n shapeInfo.sliceSize\n ];\n\n const indicesBuf = backend.bufferSync(flattenIndex);\n const xBuf = backend.bufferSync(flattenX);\n const outBuf = gatherV2Impl(xBuf, indicesBuf, flattenOutputShape);\n\n backend.disposeIntermediateTensorInfo(flattenX);\n backend.disposeIntermediateTensorInfo(flattenIndex);\n\n return backend.makeTensorInfo(\n shapeInfo.outputShape, outBuf.dtype, outBuf.values);\n}\n\nexport const gatherV2Config: KernelConfig = {\n kernelName: GatherV2,\n backendName: 'cpu',\n kernelFunc: gatherV2 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IFFT, IFFTInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {fftBatch} from '../utils/fft_utils';\nimport {reshape} from './Reshape';\n\nexport function ifft(args: {inputs: IFFTInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n const inputSize = util.sizeFromShape(input.shape);\n\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape({\n inputs: {x: input},\n backend,\n attrs: {shape: [batch, innerDimensionSize]}\n });\n\n const result = fftBatch(input2D, true, backend);\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: input.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const ifftConfig: KernelConfig = {\n kernelName: IFFT,\n backendName: 'cpu',\n kernelFunc: ifft as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IsFinite, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const isFinite =\n unaryKernelFunc(IsFinite, (xi) => Number.isFinite(xi) ? 1 : 0, 'bool');\n\nexport const isFiniteConfig: KernelConfig = {\n kernelName: IsFinite,\n backendName: 'cpu',\n kernelFunc: isFinite,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IsInf, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const isInf =\n unaryKernelFunc(IsInf, (xi) => Math.abs(xi) === Infinity ? 1 : 0, 'bool');\n\nexport const isInfConfig: KernelConfig = {\n kernelName: IsInf,\n backendName: 'cpu',\n kernelFunc: isInf,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IsNan, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const isNaN =\n unaryKernelFunc(IsNan, (xi) => Number.isNaN(xi) ? 1 : 0, 'bool');\n\nexport const isNaNConfig: KernelConfig = {\n kernelName: IsNan,\n backendName: 'cpu',\n kernelFunc: isNaN,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LinSpace, LinSpaceAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {linSpaceImpl} from './LinSpace_impl';\n\nexport function linSpace(args: {backend: MathBackendCPU, attrs: LinSpaceAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {start, stop, num} = attrs;\n\n const outVals = linSpaceImpl(start, stop, num);\n\n return backend.makeTensorInfo([outVals.length], 'float32', outVals);\n}\n\nexport const linSpaceConfig: KernelConfig = {\n kernelName: LinSpace,\n backendName: 'cpu',\n kernelFunc: linSpace as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Log1p} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const log1p = unaryKernelFunc(Log1p, (xi) => Math.log1p(xi));\n\nexport const log1pConfig: KernelConfig = {\n kernelName: Log1p,\n backendName: 'cpu',\n kernelFunc: log1p,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, LogicalAnd} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const logicalAndImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => a && b);\nexport const logicalAnd = binaryKernelFunc(\n LogicalAnd, logicalAndImpl, null /* complexImpl */, 'bool');\n\nexport const logicalAndConfig: KernelConfig = {\n kernelName: LogicalAnd,\n backendName: 'cpu',\n kernelFunc: logicalAnd\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, LogicalNot} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const logicalNot =\n unaryKernelFunc(LogicalNot, (xi) => xi ? 0 : 1, 'bool');\n\nexport const logicalNotConfig: KernelConfig = {\n kernelName: LogicalNot,\n backendName: 'cpu',\n kernelFunc: logicalNot,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, LogicalOr} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const logicalOrImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => a || b);\nexport const logicalOr =\n binaryKernelFunc(LogicalOr, logicalOrImpl, null /* complexImpl */, 'bool');\n\nexport const logicalOrConfig: KernelConfig = {\n kernelName: LogicalOr,\n backendName: 'cpu',\n kernelFunc: logicalOr\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LRN, LRNAttrs, LRNInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function lRN(\n args: {inputs: LRNInputs, backend: MathBackendCPU, attrs: LRNAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n assertNotComplex(x, 'LRN');\n\n const channels = x.shape[3];\n const maxD = channels - 1;\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const size = util.sizeFromShape(x.shape);\n const result = new Float32Array(size);\n\n function sumAcrossChannels(offset: number) {\n const currentChannel = offset % channels;\n let beginSumOffset =\n offset - currentChannel + Math.max(0, currentChannel - depthRadius);\n const endSumOffset =\n offset - currentChannel + Math.min(currentChannel + depthRadius, maxD);\n\n let sum = 0.0;\n for (; beginSumOffset <= endSumOffset; beginSumOffset++) {\n const z = xValues[beginSumOffset];\n sum += z * z;\n }\n return sum;\n }\n\n for (let offset = 0; offset < size; offset++) {\n const sum = sumAcrossChannels(offset);\n const val = xValues[offset] * Math.pow(bias + alpha * sum, -beta);\n result[offset] = val;\n }\n\n return backend.makeTensorInfo(x.shape, x.dtype, result);\n}\n\n// tslint:disable-next-line: variable-name\nexport const LRNConfig: KernelConfig = {\n kernelName: LRN,\n backendName: 'cpu',\n kernelFunc: lRN as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LRNGrad, LRNGradAttrs, LRNGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function lRNGrad(\n args:\n {inputs: LRNGradInputs, backend: MathBackendCPU, attrs: LRNGradAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, y, dy} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n assertNotComplex(dy, 'LRNGrad');\n\n const dySize = util.sizeFromShape(dy.shape);\n\n const channels = dy.shape[3];\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const yValues = backend.data.get(y.dataId).values as TypedArray;\n const result = new Float32Array(dySize);\n const size = dySize;\n\n for (let offset = 0; offset < size; offset++) {\n const currentChannel = offset % channels;\n const depthBegin =\n (offset - currentChannel) + Math.max(0, currentChannel - depthRadius);\n const depthEnd = (offset - currentChannel) +\n Math.min(channels, currentChannel + depthRadius + 1);\n\n let norm = 0;\n for (let k = depthBegin; k < depthEnd; k++) {\n norm += Math.pow(xValues[k], 2);\n }\n norm = alpha * norm + bias;\n\n for (let k = depthBegin; k < depthEnd; k++) {\n let dyi = -2 * alpha * beta * xValues[k] * yValues[offset] / norm;\n if (offset === k) {\n dyi += Math.pow(norm, -beta);\n }\n dyi *= dyValues[offset];\n result[k] += dyi;\n }\n }\n\n return backend.makeTensorInfo(dy.shape, x.dtype, result);\n}\n\n// tslint:disable-next-line: variable-name\nexport const LRNGradConfig: KernelConfig = {\n kernelName: LRNGrad,\n backendName: 'cpu',\n kernelFunc: lRNGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelFunc, Max, MaxAttrs, MaxInputs, TensorInfo} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig} from '@tensorflow/tfjs-core';\nimport {TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {maxImpl} from './Max_impl';\nimport {transposeImpl} from './Transpose_impl';\n\nexport function max(\n args: {inputs: MaxInputs, backend: MathBackendCPU, attrs: MaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {reductionIndices, keepDims} = attrs;\n const cpuBackend = backend;\n let xShape = x.shape;\n const xRank = xShape.length;\n\n const origAxes = util.parseAxisParam(reductionIndices, xShape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let xVals = cpuBackend.data.get(x.dataId).values as TypedArray;\n if (permutedAxes != null) {\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = xShape[permutedAxes[i]];\n }\n\n xVals = transposeImpl(xVals, xShape, x.dtype, permutedAxes, newShape);\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n\n xShape = newShape;\n }\n\n assertNotComplex(x, 'max');\n backend_util.assertAxesAreInnerMostDims('max', axes, xRank);\n const [maxOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(xShape, axes);\n\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const result = maxImpl(xVals, reduceSize, maxOutShape, x.dtype);\n const dataId = cpuBackend.write(result, maxOutShape, x.dtype);\n\n let outShape = maxOutShape;\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(maxOutShape, origAxes);\n outShape = newShape;\n }\n\n return {dataId, shape: outShape, dtype: x.dtype};\n}\n\nexport const maxConfig: KernelConfig = {\n kernelName: Max,\n backendName: 'cpu',\n kernelFunc: max as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool, MaxPoolAttrs, MaxPoolInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool} from '../utils/pool_utils';\nimport {identity} from './Identity';\n\nexport function maxPool(\n args:\n {inputs: MaxPoolInputs, backend: MathBackendCPU, attrs: MaxPoolAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'maxPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n let res: TensorInfo;\n\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n res = identity({inputs: {x}, backend});\n } else {\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const strides = util.computeStrides(x.shape);\n const buffer = pool(xValues, x.shape, x.dtype, strides, convInfo, 'max');\n res = backend.makeTensorInfo(\n convInfo.outShape, x.dtype, buffer.values as TypedArray);\n }\n return res;\n}\n\nexport const maxPoolConfig: KernelConfig = {\n kernelName: MaxPool,\n backendName: 'cpu',\n kernelFunc: maxPool as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool3d} from '../utils/pool_utils';\n\nexport function maxPool3D(args: {\n inputs: MaxPool3DInputs,\n backend: MathBackendCPU,\n attrs: MaxPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dimRoundingMode, dataFormat} = attrs;\n\n assertNotComplex(x, 'maxPool3d');\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode, dataFormat);\n\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const outBuf = pool3d(\n xValues, x.shape, x.dtype, util.computeStrides(x.shape), convInfo, 'max');\n\n return backend.makeTensorInfo(outBuf.shape, 'float32', outBuf.values);\n}\n\nexport const maxPool3DConfig: KernelConfig = {\n kernelName: MaxPool3D,\n backendName: 'cpu',\n kernelFunc: maxPool3D as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, buffer, KernelConfig, KernelFunc, MaxPool3DGrad, MaxPool3DGradAttrs, MaxPool3DGradInputs, Rank, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {maxPool3dPositions} from '../utils/pool_utils';\n\nexport function maxPool3DGrad(args: {\n inputs: MaxPool3DGradInputs,\n backend: MathBackendCPU,\n attrs: MaxPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n assertNotComplex([dy, input], 'maxPool3DGrad');\n\n const convInfo = backend_util.computePool3DInfo(\n input.shape as [number, number, number, number, number], filterSize,\n strides, 1 /* dilations */, pad, dimRoundingMode);\n\n const inputBuf = backend.bufferSync(input);\n const maxPosBuf = maxPool3dPositions(inputBuf, convInfo);\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx = buffer(input.shape, 'float32');\n\n const dyBuf = backend.bufferSync(dy);\n\n for (let batch = 0; batch < convInfo.batchSize; ++batch) {\n for (let channel = 0; channel < convInfo.inChannels; ++channel) {\n for (let dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {\n for (let dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {\n for (let dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {\n // Shader code begins\n const dyDepthCorner = dxDepth - padFront;\n const dyRowCorner = dxRow - padTop;\n const dyColCorner = dxCol - padLeft;\n let dotProd = 0;\n for (let wDepth = 0; wDepth < effectiveFilterDepth;\n wDepth += dilationDepth) {\n const dyDepth = (dyDepthCorner + wDepth) / strideDepth;\n if (dyDepth < 0 || dyDepth >= convInfo.outDepth ||\n Math.floor(dyDepth) !== dyDepth) {\n continue;\n }\n for (let wRow = 0; wRow < effectiveFilterHeight;\n wRow += dilationHeight) {\n const dyRow = (dyRowCorner + wRow) / strideHeight;\n if (dyRow < 0 || dyRow >= convInfo.outHeight ||\n Math.floor(dyRow) !== dyRow) {\n continue;\n }\n for (let wCol = 0; wCol < effectiveFilterWidth;\n wCol += dilationWidth) {\n const dyCol = (dyColCorner + wCol) / strideWidth;\n if (dyCol < 0 || dyCol >= convInfo.outWidth ||\n Math.floor(dyCol) !== dyCol) {\n continue;\n }\n\n const maxPos = effectiveFilterDepth * effectiveFilterHeight *\n effectiveFilterWidth -\n 1 -\n (maxPosBuf.get(batch, dyDepth, dyRow, dyCol, channel) as\n number);\n const curPos =\n wDepth * effectiveFilterHeight * effectiveFilterWidth +\n wRow * effectiveFilterWidth + wCol;\n\n const mask = maxPos === curPos ? 1 : 0;\n if (mask === 0) {\n continue;\n }\n\n const pixel =\n dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);\n dotProd += pixel * mask;\n }\n }\n }\n dx.set(dotProd, batch, dxDepth, dxRow, dxCol, channel);\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const maxPool3DGradConfig: KernelConfig = {\n kernelName: MaxPool3DGrad,\n backendName: 'cpu',\n kernelFunc: maxPool3DGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, buffer, KernelConfig, KernelFunc, MaxPoolGrad, MaxPoolGradAttrs, MaxPoolGradInputs, Rank, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {maxPoolPositions} from '../utils/pool_utils';\n\nexport function maxPoolGrad(args: {\n inputs: MaxPoolGradInputs,\n backend: MathBackendCPU,\n attrs: MaxPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input, output} = inputs;\n const x = input;\n assertNotComplex([input, output], 'maxPoolGrad');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode);\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const maxPosBuf = buffer(\n convInfo.outShape, x.dtype,\n maxPoolPositions(xValues, x.shape, x.dtype, convInfo).values);\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx =\n buffer(x.shape as [number, number, number, number], 'float32');\n\n const dyData = backend.data.get(dy.dataId).values as Float32Array;\n const dyBuf = buffer(\n dy.shape as [number, number, number, number], 'float32', dyData);\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let d = 0; d < convInfo.inChannels; ++d) {\n for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {\n for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {\n // Shader code begins.\n const dyRCorner = dxR - padTop;\n const dyCCorner = dxC - padLeft;\n let dotProd = 0;\n for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {\n const dyR = (dyRCorner + wR) / strideHeight;\n if (dyR < 0 || dyR >= convInfo.outHeight ||\n Math.floor(dyR) !== dyR) {\n continue;\n }\n for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {\n const dyC = (dyCCorner + wC) / strideWidth;\n if (dyC < 0 || dyC >= convInfo.outWidth ||\n Math.floor(dyC) !== dyC) {\n continue;\n }\n const maxPos = effectiveFilterHeight * effectiveFilterWidth - 1 -\n (maxPosBuf.get(b, dyR, dyC, d) as number);\n const curPos = wR * effectiveFilterWidth + wC;\n\n const mask = maxPos === curPos ? 1 : 0;\n if (mask === 0) {\n continue;\n }\n\n const pixel = dyBuf.get(b, dyR, dyC, d);\n dotProd += pixel * mask;\n }\n }\n dx.set(dotProd, b, dxR, dxC, d);\n }\n }\n }\n }\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const maxPoolGradConfig: KernelConfig = {\n kernelName: MaxPoolGrad,\n backendName: 'cpu',\n kernelFunc: maxPoolGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig, TypedArray} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {maxPoolWithArgmaxImpl} from './MaxPoolWithArgmax_impl';\n\nexport const maxPoolWithArgmaxConfig: KernelConfig = {\n kernelName: MaxPoolWithArgmax,\n backendName: 'cpu',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {x} = inputs as MaxPoolWithArgmaxInputs;\n const {filterSize, strides, pad, includeBatchInIndex} =\n attrs as unknown as MaxPoolWithArgmaxAttrs;\n const cpuBackend = backend as MathBackendCPU;\n assertNotComplex(x, 'MaxPoolWithArgmax');\n\n const values = cpuBackend.data.get(x.dataId).values as TypedArray;\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n [1, 1], pad);\n const [pooled, indexes] = maxPoolWithArgmaxImpl(\n values, x.shape, x.dtype, includeBatchInIndex, convInfo);\n\n const pooledDataId =\n cpuBackend.write(pooled as Float32Array, convInfo.outShape, x.dtype);\n const indexesDataId =\n cpuBackend.write(indexes as Int32Array, convInfo.outShape, x.dtype);\n return [\n {dataId: pooledDataId, shape: convInfo.outShape, dtype: x.dtype},\n {dataId: indexesDataId, shape: convInfo.outShape, dtype: 'int32'}\n ];\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {maxPoolPositions, pool} from '../utils/pool_utils';\nexport function maxPoolWithArgmaxImpl(\n xValues: TypedArray, xShape: number[], dtype: DataType,\n includeBatchInIndex: boolean, convInfo: backend_util.Conv2DInfo) {\n const strides = util.computeStrides(xShape);\n const maxPools = pool(xValues, xShape, dtype, strides, convInfo, 'max');\n const maxPositions = maxPoolPositions(\n xValues, xShape, dtype, convInfo, true, includeBatchInIndex);\n\n return [maxPools.values, maxPositions.values];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Mean, MeanAttrs, MeanInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {cast} from './Cast';\nimport {div} from './RealDiv';\nimport {sum} from './Sum';\n\nexport function mean(\n args: {inputs: MeanInputs, backend: MathBackendCPU, attrs: MeanAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const axes = util.parseAxisParam(axis, x.shape);\n const shapes = backend_util.computeOutAndReduceShapes(x.shape, axes);\n const reduceShape = shapes[1];\n const reduceSize = util.sizeFromShape(reduceShape);\n const toDispose = [];\n const reduceSizeScalar =\n backend.makeTensorInfo([], 'float32', new Float32Array([reduceSize]));\n toDispose.push(reduceSizeScalar);\n\n const $x = cast({inputs: {x}, backend, attrs: {dtype: 'float32'}});\n toDispose.push($x);\n\n const res =\n div({inputs: {a: $x, b: reduceSizeScalar}, backend}) as TensorInfo;\n toDispose.push(res);\n\n const result = sum({inputs: {x: res}, backend, attrs: {axis, keepDims}});\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const meanConfig: KernelConfig = {\n kernelName: Mean,\n backendName: 'cpu',\n kernelFunc: mean as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Min, MinAttrs, MinInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function min(\n args: {inputs: MinInputs, backend: MathBackendCPU, attrs: MinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'min');\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('min', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = util.makeZerosTypedArray(util.sizeFromShape(outShape), $x.dtype);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let min = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (Number.isNaN(value) ||\n value < min) { // comparison with NaN always return false\n min = value;\n }\n }\n vals[i] = min;\n }\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo($x);\n }\n\n const result = backend.makeTensorInfo(outShape, $x.dtype, vals);\n\n if (keepDims) {\n const expandedShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n const reshapedResult =\n reshape({inputs: {x: result}, backend, attrs: {shape: expandedShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n }\n\n return result;\n}\n\nexport const minConfig: KernelConfig = {\n kernelName: Min,\n backendName: 'cpu',\n kernelFunc: min as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, MirrorPad, MirrorPadAttrs, MirrorPadInputs, NumericDataType, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function mirrorPad(args: {\n inputs: MirrorPadInputs,\n backend: MathBackendCPU,\n attrs: MirrorPadAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {paddings, mode} = attrs;\n\n assertNotComplex(x, 'mirrorPad');\n\n const outShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n\n const start = paddings.map(p => p[0]);\n const end = paddings.map((p, i) => p[0] + x.shape[i]);\n const offset = mode === 'reflect' ? 0 : 1;\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const xRank = x.shape.length;\n const xStrides = util.computeStrides(x.shape);\n\n const resultSize = util.sizeFromShape(outShape);\n const resultRank = outShape.length;\n const resultStrides = util.computeStrides(outShape);\n const resVals =\n util.getTypedArrayFromDType(x.dtype as NumericDataType, resultSize);\n\n for (let i = 0; i < resultSize; i++) {\n let coords = util.indexToLoc(i, resultRank, resultStrides);\n for (let i = 0; i < resultRank; i++) {\n if (coords[i] < start[i]) {\n coords[i] = start[i] * 2 - coords[i] - offset;\n } else if (coords[i] >= end[i]) {\n coords[i] = (end[i] - 1) * 2 - coords[i] + offset;\n }\n }\n coords = coords.map((c, i) => c - start[i]);\n\n const inIndex = util.locToIndex(coords, xRank, xStrides);\n\n resVals[i] = xVals[inIndex];\n }\n\n const outId = backend.write(resVals, outShape, x.dtype);\n\n return {dataId: outId, shape: outShape, dtype: x.dtype};\n}\n\nexport const mirrorPadConfig: KernelConfig = {\n kernelName: MirrorPad,\n backendName: 'cpu',\n kernelFunc: mirrorPad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Mod} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const modImpl =\n createSimpleBinaryKernelImpl(((aValue: number, bValue: number) => {\n const rem = aValue % bValue;\n if ((aValue < 0 && bValue < 0) || (aValue >= 0 && bValue >= 0)) {\n return rem;\n } else {\n return (rem + bValue) % bValue;\n }\n }));\n\nexport const mod = binaryKernelFunc(Mod, modImpl);\n\nexport const modConfig: KernelConfig = {\n kernelName: Mod,\n backendName: 'cpu',\n kernelFunc: mod\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Softmax, SoftmaxAttrs, SoftmaxInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {exp} from './Exp';\nimport {max} from './Max';\nimport {div} from './RealDiv';\nimport {reshape} from './Reshape';\nimport {sub} from './Sub';\nimport {sum} from './Sum';\n\nexport function softmax(\n args:\n {inputs: SoftmaxInputs, backend: MathBackendCPU, attrs: SoftmaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {dim} = attrs;\n\n const logitsRank = logits.shape.length;\n\n let $dim = dim;\n if ($dim === -1) {\n $dim = logitsRank - 1;\n }\n if ($dim !== logitsRank - 1) {\n throw Error(\n 'Softmax along a non-last dimension is not yet supported. ' +\n `Logits was rank ${logitsRank} and dim was ${$dim}`);\n }\n\n const axes = util.parseAxisParam([$dim], logits.shape);\n const maxLogit = max({\n inputs: {x: logits},\n backend,\n attrs: {reductionIndices: axes, keepDims: false}\n });\n const expandedShape = backend_util.expandShapeToKeepDim(maxLogit.shape, axes);\n\n const maxLogitReshaped =\n reshape({inputs: {x: maxLogit}, backend, attrs: {shape: expandedShape}});\n const a =\n sub({inputs: {a: logits, b: maxLogitReshaped}, backend}) as TensorInfo;\n const b = exp({inputs: {x: a}, backend}) as TensorInfo;\n const sumExp =\n sum({inputs: {x: b}, backend, attrs: {axis: axes, keepDims: false}});\n const sumReshaped =\n reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}});\n\n const result = div({inputs: {a: b, b: sumReshaped}, backend}) as TensorInfo;\n\n backend.disposeIntermediateTensorInfo(maxLogit);\n backend.disposeIntermediateTensorInfo(maxLogitReshaped);\n backend.disposeIntermediateTensorInfo(a);\n backend.disposeIntermediateTensorInfo(b);\n backend.disposeIntermediateTensorInfo(sumExp);\n backend.disposeIntermediateTensorInfo(sumReshaped);\n\n return result;\n}\n\nexport const softmaxConfig: KernelConfig = {\n kernelName: Softmax,\n backendName: 'cpu',\n kernelFunc: softmax as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Multinomial, MultinomialAttrs, MultinomialInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\nimport * as seedrandom from 'seedrandom';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {softmax} from './Softmax';\n\nexport function multinomial(args: {\n inputs: MultinomialInputs,\n backend: MathBackendCPU,\n attrs: MultinomialAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {numSamples, seed, normalized} = attrs;\n\n assertNotComplex(logits, 'multinomial');\n\n const probabilities = normalized ?\n logits :\n softmax({inputs: {logits}, backend, attrs: {dim: -1}});\n\n const batchSize = probabilities.shape[0];\n const numEvents = probabilities.shape[1];\n const probVals = backend.data.get(probabilities.dataId).values as TypedArray;\n const resShape = [batchSize, numSamples];\n const resVals =\n util.makeZerosTypedArray(util.sizeFromShape(resShape), 'int32');\n\n for (let b = 0; b < batchSize; ++b) {\n const offset = b * numEvents;\n // The cdf won't include the last event. It will be implicit if no other\n // event happened.\n const cdf = new Float32Array(numEvents - 1);\n cdf[0] = probVals[offset];\n for (let event = 1; event < cdf.length; ++event) {\n cdf[event] = cdf[event - 1] + probVals[offset + event];\n }\n\n const random = seedrandom.alea(seed.toString());\n const outOffset = b * numSamples;\n for (let sampleId = 0; sampleId < numSamples; ++sampleId) {\n const r = random();\n\n // Assume last event happened by default.\n resVals[outOffset + sampleId] = cdf.length;\n\n for (let event = 0; event < cdf.length; event++) {\n if (r < cdf[event]) {\n resVals[outOffset + sampleId] = event;\n break;\n }\n }\n }\n }\n\n if (!normalized) {\n backend.disposeIntermediateTensorInfo(probabilities);\n }\n\n return backend.makeTensorInfo(resShape, 'int32', resVals);\n}\n\nexport const multinomialConfig: KernelConfig = {\n kernelName: Multinomial,\n backendName: 'cpu',\n kernelFunc: multinomial as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV3, NonMaxSuppressionV3Attrs, NonMaxSuppressionV3Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV3Impl = kernel_impls.nonMaxSuppressionV3Impl;\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function nonMaxSuppressionV3(args: {\n inputs: NonMaxSuppressionV3Inputs,\n backend: MathBackendCPU,\n attrs: NonMaxSuppressionV3Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold} = attrs;\n\n assertNotComplex(boxes, 'NonMaxSuppression');\n\n const boxesVals = backend.data.get(boxes.dataId).values as TypedArray;\n const scoresVals = backend.data.get(scores.dataId).values as TypedArray;\n\n const {selectedIndices} = nonMaxSuppressionV3Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n\n return backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices));\n}\n\nexport const nonMaxSuppressionV3Config: KernelConfig = {\n kernelName: NonMaxSuppressionV3,\n backendName: 'cpu',\n kernelFunc: nonMaxSuppressionV3 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV4Impl = kernel_impls.nonMaxSuppressionV4Impl;\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function nonMaxSuppressionV4(args: {\n inputs: NonMaxSuppressionV4Inputs,\n backend: MathBackendCPU,\n attrs: NonMaxSuppressionV4Attrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize} =\n attrs;\n\n assertNotComplex(boxes, 'NonMaxSuppressionPadded');\n\n const boxesVals = backend.data.get(boxes.dataId).values as TypedArray;\n const scoresVals = backend.data.get(scores.dataId).values as TypedArray;\n\n const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n padToMaxOutputSize);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo([], 'int32', new Int32Array([validOutputs]))\n ];\n}\nexport const nonMaxSuppressionV4Config: KernelConfig = {\n kernelName: NonMaxSuppressionV4,\n backendName: 'cpu',\n kernelFunc: nonMaxSuppressionV4 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV5Impl = kernel_impls.nonMaxSuppressionV5Impl;\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function nonMaxSuppressionV5(args: {\n inputs: NonMaxSuppressionV5Inputs,\n backend: MathBackendCPU,\n attrs: NonMaxSuppressionV5Attrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma} = attrs;\n\n assertNotComplex(boxes, 'NonMaxSuppressionWithScore');\n\n const boxesVals = backend.data.get(boxes.dataId).values as TypedArray;\n const scoresVals = backend.data.get(scores.dataId).values as TypedArray;\n\n const maxOutputSizeVal = maxOutputSize;\n const iouThresholdVal = iouThreshold;\n const scoreThresholdVal = scoreThreshold;\n const softNmsSigmaVal = softNmsSigma;\n\n const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal,\n scoreThresholdVal, softNmsSigmaVal);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo(\n [selectedScores.length], 'float32', new Float32Array(selectedScores))\n ];\n}\n\nexport const nonMaxSuppressionV5Config: KernelConfig = {\n kernelName: NonMaxSuppressionV5,\n backendName: 'cpu',\n kernelFunc: nonMaxSuppressionV5 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, OneHot, OneHotAttrs, OneHotInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function oneHot(\n args: {inputs: OneHotInputs, backend: MathBackendCPU, attrs: OneHotAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {indices} = inputs;\n const {dtype, depth, onValue, offValue} = attrs;\n\n assertNotComplex(indices, 'oneHot');\n\n const indicesSize = util.sizeFromShape(indices.shape);\n\n const res = new Float32Array(indicesSize * depth);\n res.fill(offValue);\n const indicesVal = backend.data.get(indices.dataId).values as TypedArray;\n\n for (let event = 0; event < indicesSize; ++event) {\n if (indicesVal[event] >= 0 && indicesVal[event] < depth) {\n res[event * depth + indicesVal[event]] = onValue;\n }\n }\n\n return backend.makeTensorInfo([...indices.shape, depth], dtype, res);\n}\n\nexport const oneHotConfig: KernelConfig = {\n kernelName: OneHot,\n backendName: 'cpu',\n kernelFunc: oneHot as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, ZerosLike, ZerosLikeInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\n\nexport function zerosLike(\n args: {inputs: ZerosLikeInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'string') {\n throw new Error('zerosLike is not supported for string tensors');\n } else if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = zerosLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n return fill({backend, attrs: {shape: x.shape, value: 0, dtype: x.dtype}});\n }\n}\n\nexport const zerosLikeConfig: KernelConfig = {\n kernelName: ZerosLike,\n backendName: 'cpu',\n kernelFunc: zerosLike as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, OnesLike, OnesLikeInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {zerosLike} from './ZerosLike';\n\nexport function onesLike(\n args: {inputs: OnesLikeInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'string') {\n throw new Error('onesLike is not supported for string tensors');\n } else if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = onesLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n return fill({backend, attrs: {shape: x.shape, value: 1, dtype: x.dtype}});\n }\n}\n\nexport const onesLikeConfig: KernelConfig = {\n kernelName: OnesLike,\n backendName: 'cpu',\n kernelFunc: onesLike as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Pack, PackAttrs, PackInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {concat} from './Concat';\nimport {expandDims} from './ExpandDims';\n\nexport function pack(\n args: {inputs: PackInputs, backend: MathBackendCPU, attrs: PackAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {axis} = attrs;\n\n if (inputs.length === 1) {\n return expandDims(\n {inputs: {input: inputs[0]}, backend, attrs: {dim: axis}});\n }\n\n const shape = inputs[0].shape;\n const dtype = inputs[0].dtype;\n\n inputs.forEach(t => {\n util.assertShapesMatch(\n shape, t.shape,\n 'All tensors passed to stack must have matching shapes');\n util.assert(\n dtype === t.dtype,\n () => 'All tensors passed to stack must have matching dtypes');\n });\n\n const intermediateTensorInfos: TensorInfo[] = [];\n const expandedTensors = inputs.map(t => {\n const expandedT =\n expandDims({inputs: {input: t}, backend, attrs: {dim: axis}});\n intermediateTensorInfos.push(expandedT);\n return expandedT;\n });\n\n const result = concat({inputs: expandedTensors, backend, attrs: {axis}});\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const packConfig: KernelConfig = {\n kernelName: Pack,\n backendName: 'cpu',\n kernelFunc: pack as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, NumericDataType, PadV2, PadV2Attrs, PadV2Inputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function padV2(\n args: {inputs: PadV2Inputs, backend: MathBackendCPU, attrs: PadV2Attrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {paddings, constantValue} = attrs;\n\n assertNotComplex(x, 'pad');\n\n const outShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n\n const start = paddings.map(p => p[0]);\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const xSize = util.sizeFromShape(x.shape);\n const xRank = x.shape.length;\n const xStrides = util.computeStrides(x.shape);\n\n const resultSize = util.sizeFromShape(outShape);\n const resultRank = outShape.length;\n const resultStrides = util.computeStrides(outShape);\n const resVals =\n util.getTypedArrayFromDType(x.dtype as NumericDataType, resultSize);\n\n if (constantValue !== 0) {\n resVals.fill(constantValue);\n }\n\n for (let i = 0; i < xSize; i++) {\n const coords = util.indexToLoc(i, xRank, xStrides);\n const outCoords = coords.map((c, i) => c + start[i]);\n const outIndex = util.locToIndex(outCoords, resultRank, resultStrides);\n\n resVals[outIndex] = xVals[i];\n }\n\n const outId = backend.write(resVals, outShape, x.dtype);\n\n return {dataId: outId, shape: outShape, dtype: x.dtype};\n}\n\nexport const padV2Config: KernelConfig = {\n kernelName: PadV2,\n backendName: 'cpu',\n kernelFunc: padV2 as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Pow} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const powImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => Math.pow(a, b));\nexport const pow = binaryKernelFunc(Pow, powImpl);\n\nexport const powConfig: KernelConfig = {\n kernelName: Pow,\n backendName: 'cpu',\n kernelFunc: pow\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, RaggedGather, RaggedGatherAttrs, RaggedGatherInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {raggedGatherImpl} from './RaggedGather_impl';\n\nexport function raggedGather(args: {\n inputs: RaggedGatherInputs,\n backend: MathBackendCPU,\n attrs: RaggedGatherAttrs\n}): TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {paramsNestedSplits, paramsDenseValues, indices} = inputs;\n const {outputRaggedRank} = attrs;\n\n const $paramsNestedSplits = paramsNestedSplits.map(\n t => backend.data.get(t.dataId).values as TypedArray);\n const $paramsNestedSplitsShapes = paramsNestedSplits.map(t => t.shape);\n const $paramsDenseValues =\n backend.data.get(paramsDenseValues.dataId).values as TypedArray;\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n\n const [outputNestedSplits, outputDenseValues, outputDenseValuesShape] =\n raggedGatherImpl(\n $paramsNestedSplits, $paramsNestedSplitsShapes, $paramsDenseValues,\n paramsDenseValues.shape, paramsDenseValues.dtype, $indices,\n indices.shape, outputRaggedRank);\n\n const outputNestedSplitsTensors = outputNestedSplits.map(\n (splits) => backend.makeTensorInfo([splits.length], 'int32', splits));\n\n const outputDenseValuesTensor = backend.makeTensorInfo(\n outputDenseValuesShape, paramsDenseValues.dtype, outputDenseValues);\n\n return outputNestedSplitsTensors.concat([outputDenseValuesTensor]);\n}\n\nexport const raggedGatherConfig: KernelConfig = {\n kernelName: RaggedGather,\n backendName: 'cpu',\n kernelFunc: raggedGather as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, RaggedRange, RaggedRangeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {raggedRangeImpl} from './RaggedRange_impl';\n\nexport function raggedRange(\n args: {inputs: RaggedRangeInputs, backend: MathBackendCPU}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {starts, limits, deltas} = inputs;\n\n const $starts = backend.data.get(starts.dataId).values as TypedArray;\n const $limits = backend.data.get(limits.dataId).values as TypedArray;\n const $deltas = backend.data.get(deltas.dataId).values as TypedArray;\n\n const [rtNestedSplitsData, rtDenseValuesData] = raggedRangeImpl(\n $starts, starts.shape, starts.dtype, $limits, limits.shape, $deltas,\n deltas.shape);\n\n const rtNestedSplits = backend.makeTensorInfo(\n [rtNestedSplitsData.length], 'int32', rtNestedSplitsData);\n const rtDenseValues = backend.makeTensorInfo(\n [rtDenseValuesData.length], starts.dtype, rtDenseValuesData);\n\n return [rtNestedSplits, rtDenseValues];\n}\n\nexport const raggedRangeConfig: KernelConfig = {\n kernelName: RaggedRange,\n backendName: 'cpu',\n kernelFunc: raggedRange as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, RaggedTensorToTensor, RaggedTensorToTensorAttrs, RaggedTensorToTensorInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {raggedTensorToTensorImpl} from './RaggedTensorToTensor_impl';\n\nexport function raggedTensorToTensor(args: {\n inputs: RaggedTensorToTensorInputs,\n backend: MathBackendCPU,\n attrs: RaggedTensorToTensorAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {shape, values, defaultValue, rowPartitionTensors} = inputs;\n const {rowPartitionTypes} = attrs;\n\n const $shape = backend.data.get(shape.dataId).values as TypedArray;\n const $values = backend.data.get(values.dataId).values as TypedArray;\n const $defaultValue =\n backend.data.get(defaultValue.dataId).values as TypedArray;\n const $rowPartitionValues = rowPartitionTensors.map(\n t => backend.data.get(t.dataId).values as TypedArray);\n const rowPartitionValuesShapes = rowPartitionTensors.map(t => t.shape);\n\n const [outputShape, output] = raggedTensorToTensorImpl(\n $shape, shape.shape, $values, values.shape, values.dtype, $defaultValue,\n defaultValue.shape, $rowPartitionValues, rowPartitionValuesShapes,\n rowPartitionTypes);\n return backend.makeTensorInfo(outputShape, values.dtype, output);\n}\n\nexport const raggedTensorToTensorConfig: KernelConfig = {\n kernelName: RaggedTensorToTensor,\n backendName: 'cpu',\n kernelFunc: raggedTensorToTensor as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Range, RangeAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {rangeImpl} from './Range_impl';\n\nexport function range(args: {backend: MathBackendCPU, attrs: RangeAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {start, stop, dtype, step} = attrs;\n\n const values = rangeImpl(start, stop, step, dtype);\n return backend.makeTensorInfo([values.length], dtype, values);\n}\n\nexport const rangeConfig: KernelConfig = {\n kernelName: Range,\n backendName: 'cpu',\n kernelFunc: range as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Reciprocal} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const reciprocal = unaryKernelFunc(Reciprocal, (xi) => 1 / xi);\n\nexport const reciprocalConfig: KernelConfig = {\n kernelName: Reciprocal,\n backendName: 'cpu',\n kernelFunc: reciprocal,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeBilinear(args: {\n inputs: ResizeBilinearInputs,\n backend: MathBackendCPU,\n attrs: ResizeBilinearAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n assertNotComplex(images, 'resizeBilinear');\n\n const imagesStrides = util.computeStrides(images.shape);\n const [newHeight, newWidth] = size;\n\n const [batch, oldHeight, oldWidth, numChannels] = images.shape;\n const xValues = backend.data.get(images.dataId).values as TypedArray;\n const result = new Float32Array(\n util.sizeFromShape([batch, newHeight, newWidth, numChannels]));\n\n const effectiveInputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n let outputIdx = 0;\n const effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];\n const effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];\n for (let b = 0; b < batch; b++) {\n for (let r = 0; r < newHeight; r++) {\n let sourceFracRow: number;\n if (halfPixelCenters) {\n sourceFracRow = effectiveRowSizeRatio * (r + 0.5) - 0.5;\n } else {\n sourceFracRow = effectiveRowSizeRatio * r;\n }\n\n const sourceRowFloor = Math.max(0, Math.floor(sourceFracRow));\n const rowFrac = sourceFracRow - sourceRowFloor;\n const sourceRowCeil = Math.min(oldHeight - 1, Math.ceil(sourceFracRow));\n const topRowOffset =\n b * imagesStrides[0] + sourceRowFloor * imagesStrides[1];\n const botRowOffset =\n b * imagesStrides[0] + sourceRowCeil * imagesStrides[1];\n for (let c = 0; c < newWidth; c++) {\n let sourceFracCol: number;\n if (halfPixelCenters) {\n sourceFracCol = effectiveColSizeRatio * (c + 0.5) - 0.5;\n } else {\n sourceFracCol = effectiveColSizeRatio * c;\n }\n const sourceColFloor = Math.max(0, Math.floor(sourceFracCol));\n const colFrac = sourceFracCol - sourceColFloor;\n const sourceColCeil = Math.min(oldWidth - 1, Math.ceil(sourceFracCol));\n const topLeftOffest = topRowOffset + sourceColFloor * imagesStrides[2];\n const botLeftOffset = botRowOffset + sourceColFloor * imagesStrides[2];\n const topRightOffset = topRowOffset + sourceColCeil * imagesStrides[2];\n const botRightOffest = botRowOffset + sourceColCeil * imagesStrides[2];\n for (let d = 0; d < numChannels; d++) {\n // Begin shader.\n\n // Compute the fractional index of the source.\n const topLeft = xValues[topLeftOffest + d];\n const bottomLeft = xValues[botLeftOffset + d];\n const topRight = xValues[topRightOffset + d];\n const bottomRight = xValues[botRightOffest + d];\n\n const top = topLeft + (topRight - topLeft) * colFrac;\n const bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;\n const newValue = top + (bottom - top) * rowFrac;\n\n result[outputIdx++] = newValue;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batch, newHeight, newWidth, numChannels], 'float32', result);\n}\n\nexport const resizeBilinearConfig: KernelConfig = {\n kernelName: ResizeBilinear,\n backendName: 'cpu',\n kernelFunc: resizeBilinear as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeBilinearGrad, ResizeBilinearGradAttrs, ResizeBilinearGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeBilinearGrad(args: {\n inputs: ResizeBilinearGradInputs,\n backend: MathBackendCPU,\n attrs: ResizeBilinearGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n assertNotComplex([dy, images], 'resizeBilinearGrad');\n\n const imagesStrides = util.computeStrides(images.shape);\n\n const [batch, xHeight, xWidth, depth] = images.shape;\n const [, yHeight, yWidth] = dy.shape;\n\n const output = new Float32Array(batch * xHeight * xWidth * depth);\n\n // In the backwards pass, we want to find the pixels that were generated\n // for each pixel in the input image the forward pass and add the\n // corresponding coefficient from dy to the gradient (with some\n // interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/3039375c86a5bbc9610c7725dcaa95d635f87ba2/tensorflow/core/kernels/resize_bilinear_op.cc#L275\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n let offset = 0;\n for (let b = 0; b < batch; b++) {\n const bOffset = b * imagesStrides[0];\n for (let r = 0; r < yHeight; r++) {\n const dxR = r * heightScale;\n const topDxRIndex = Math.floor(dxR);\n const bottomDxRIndex = Math.min(Math.ceil(dxR), xHeight - 1);\n\n const topDxROffset = bOffset + topDxRIndex * imagesStrides[1];\n const bottomDxROffset = bOffset + bottomDxRIndex * imagesStrides[1];\n\n const dxRLerp = dxR - topDxRIndex;\n const inverseDxRLerp = 1.0 - dxRLerp;\n for (let c = 0; c < yWidth; c++) {\n const dxC = c * widthScale;\n const leftDxCIndex = Math.floor(dxC);\n const rightDxCIndex = Math.min(Math.ceil(dxC), xWidth - 1);\n const dxCLerp = dxC - leftDxCIndex;\n const inverseDxCLerp = 1.0 - dxCLerp;\n\n const topLeftRCOffset = topDxROffset + leftDxCIndex * imagesStrides[2];\n const topRightRCOffset =\n topDxROffset + rightDxCIndex * imagesStrides[2];\n const bottomLeftRCOffset =\n bottomDxROffset + leftDxCIndex * imagesStrides[2];\n const bottomRightRCOffset =\n bottomDxROffset + rightDxCIndex * imagesStrides[2];\n\n const inverseDxRLerpTimesInverseDxCLerp =\n inverseDxRLerp * inverseDxCLerp;\n const inverseDxRLerpTimesDxCLerp = inverseDxRLerp * dxCLerp;\n const dxRLerpTimesInverseDxCLerp = dxRLerp * inverseDxCLerp;\n const dxRLerpTimesDxCLerp = dxRLerp * dxCLerp;\n for (let d = 0; d < depth; d++) {\n const dyVal = dyValues[offset++];\n output[topLeftRCOffset + d] +=\n dyVal * inverseDxRLerpTimesInverseDxCLerp;\n output[topRightRCOffset + d] += dyVal * inverseDxRLerpTimesDxCLerp;\n output[bottomLeftRCOffset + d] += dyVal * dxRLerpTimesInverseDxCLerp;\n output[bottomRightRCOffset + d] += dyVal * dxRLerpTimesDxCLerp;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batch, xWidth, xHeight, depth], 'float32', output);\n}\n\nexport const resizeBilinearGradConfig: KernelConfig = {\n kernelName: ResizeBilinearGrad,\n backendName: 'cpu',\n kernelFunc: resizeBilinearGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeNearestNeighbor(args: {\n inputs: ResizeNearestNeighborInputs,\n backend: MathBackendCPU,\n attrs: ResizeNearestNeighborAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n assertNotComplex(images, 'resizeNearestNeighbor');\n\n const imagesStrides = util.computeStrides(images.shape);\n const [newHeight, newWidth] = size;\n\n const [batch, oldHeight, oldWidth, numChannels] = images.shape;\n const xValues = backend.data.get(images.dataId).values as TypedArray;\n const output = new Float32Array(batch * newHeight * newWidth * numChannels);\n\n const effectiveInputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n const effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];\n const effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];\n\n let outputOffset = 0;\n for (let b = 0; b < batch; b++) {\n const batchOffset = b * imagesStrides[0];\n for (let r = 0; r < newHeight; r++) {\n const sourceFracRow = halfPixelCenters ?\n effectiveRowSizeRatio * (r + 0.5) :\n effectiveRowSizeRatio * r;\n let sourceNearestRow = Math.min(\n oldHeight - 1,\n alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow));\n if (halfPixelCenters) {\n sourceNearestRow = Math.max(0, sourceNearestRow);\n }\n const rowOffset = batchOffset + sourceNearestRow * imagesStrides[1];\n for (let c = 0; c < newWidth; c++) {\n const sourceFracCol = halfPixelCenters ?\n effectiveColSizeRatio * (c + 0.5) :\n effectiveColSizeRatio * c;\n let sourceNearestCol = Math.min(\n oldWidth - 1,\n alignCorners ? Math.round(sourceFracCol) :\n Math.floor(sourceFracCol));\n if (halfPixelCenters) {\n sourceNearestCol = Math.max(0, sourceNearestCol);\n }\n const colOffset = rowOffset + sourceNearestCol * imagesStrides[2];\n for (let d = 0; d < numChannels; d++) {\n // Begin shader.\n // Compute the fractional index of the source.\n const newVal = xValues[colOffset + d];\n output[outputOffset++] = newVal;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batch, newHeight, newWidth, numChannels], images.dtype, output);\n}\n\nexport const resizeNearestNeighborConfig: KernelConfig = {\n kernelName: ResizeNearestNeighbor,\n backendName: 'cpu',\n kernelFunc: resizeNearestNeighbor as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeNearestNeighborGrad, ResizeNearestNeighborGradAttrs, ResizeNearestNeighborGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeNearestNeighborGrad(args: {\n inputs: ResizeNearestNeighborGradInputs,\n backend: MathBackendCPU,\n attrs: ResizeNearestNeighborGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n assertNotComplex([dy, images], 'resizeNearestNeighborGrad');\n\n const imagesStrides = util.computeStrides(images.shape);\n const dyStrides = util.computeStrides(dy.shape);\n const [batch, xHeight, xWidth, depth] = images.shape;\n const [, yHeight, yWidth] = dy.shape;\n\n const output = new Float32Array(batch * xHeight * xWidth * depth);\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n\n // In the backwards pass, we want to find the pixels that were generated\n // for each pixel in the input image the forward pass\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n // Loop over the output space.\n for (let b = 0; b < batch; b++) {\n const batchOffset = b * imagesStrides[0];\n for (let r = 0; r < xHeight; r++) {\n const rowOffset = batchOffset + r * imagesStrides[1];\n\n // Compute bounds for where in dy we will look\n const startRLerp = Math.floor(r * invHeightScale);\n const startDyR = Math.floor(startRLerp - (winHeight / 2));\n for (let c = 0; c < xWidth; c++) {\n const colOffset = rowOffset + c * imagesStrides[2];\n\n // Compute bounds for where in dy we will look\n const startCLerp = Math.floor(c * invWidthScale);\n const startDyC = Math.floor(startCLerp - (winWidth / 2));\n\n for (let d = 0; d < depth; d++) {\n let accum = 0;\n // loop over dy\n\n for (let dyRIndex = 0; dyRIndex < winHeight; dyRIndex++) {\n const dyR = dyRIndex + startDyR;\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= yHeight) {\n continue;\n }\n\n const dyROffset = batchOffset + dyR * dyStrides[1];\n const sourceFracRow = dyR * heightScale;\n const sourceNearestRow = Math.min(\n xHeight - 1,\n alignCorners ? Math.round(sourceFracRow) :\n Math.floor(sourceFracRow));\n if (r !== sourceNearestRow) {\n continue;\n }\n for (let dyCIndex = 0; dyCIndex < winWidth; dyCIndex++) {\n const dyC = dyCIndex + startDyC;\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= yWidth) {\n continue;\n }\n\n const dyCOffset = dyROffset + dyC * dyStrides[2];\n const sourceFracCol = dyC * widthScale;\n const sourceNearestCol = Math.min(\n xWidth - 1,\n alignCorners ? Math.round(sourceFracCol) :\n Math.floor(sourceFracCol));\n\n if (c === sourceNearestCol) {\n accum += dyValues[dyCOffset + d];\n }\n }\n }\n output[colOffset + d] = accum;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(images.shape, images.dtype, output);\n}\n\nexport const resizeNearestNeighborGradConfig: KernelConfig = {\n kernelName: ResizeNearestNeighborGrad,\n backendName: 'cpu',\n kernelFunc: resizeNearestNeighborGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Reverse, ReverseAttrs, ReverseInputs, TensorBuffer, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {identity} from './Identity';\n\nexport function reverse(\n args:\n {inputs: ReverseInputs, backend: MathBackendCPU, attrs: ReverseAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dims} = attrs;\n\n assertNotComplex(x, 'reverse');\n\n const xRank = x.shape.length;\n\n const $dims = util.parseAxisParam(dims, x.shape);\n if (xRank === 0) {\n return identity({inputs: {x}, backend});\n }\n\n const outBuf = new TensorBuffer(x.shape, x.dtype);\n const xBuf = backend.bufferSync(x);\n\n for (let i = 0; i < outBuf.size; i++) {\n const outLoc = outBuf.indexToLoc(i);\n const inLoc = outLoc.slice();\n $dims.forEach(d => inLoc[d] = x.shape[d] - 1 - inLoc[d]);\n outBuf.set(xBuf.get(...inLoc), ...outLoc);\n }\n\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const reverseConfig: KernelConfig = {\n kernelName: Reverse,\n backendName: 'cpu',\n kernelFunc: reverse as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, NumericDataType, TypedArray} from '@tensorflow/tfjs-core';\nimport {backend_util, RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const rotateWithOffsetConfig: KernelConfig = {\n kernelName: RotateWithOffset,\n backendName: 'cpu',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as RotateWithOffsetInputs;\n const {radians, fillValue, center} =\n attrs as unknown as RotateWithOffsetAttrs;\n const cpuBackend = backend as MathBackendCPU;\n\n const output = util.getTypedArrayFromDType(\n image.dtype as NumericDataType, util.sizeFromShape(image.shape));\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n\n const [centerX, centerY] =\n backend_util.getImageCenter(center, imageHeight, imageWidth);\n const fullOpacityValue = 255;\n\n const sinFactor = Math.sin(radians);\n const cosFactor = Math.cos(radians);\n const imageVals = cpuBackend.data.get(image.dataId).values as TypedArray;\n\n for (let batchIdx = 0; batchIdx < batch; batchIdx++) {\n const batchOffset = batchIdx * imageWidth * imageHeight * numChannels;\n\n for (let row = 0; row < imageHeight; row++) {\n const rowOffset = row * (imageWidth * numChannels);\n\n for (let col = 0; col < imageWidth; col++) {\n const colOffset = col * numChannels;\n\n for (let channel = 0; channel < numChannels; channel++) {\n const coords = [batch, row, col, channel];\n\n const x = coords[2];\n const y = coords[1];\n\n // coordX/coordY are the result of rotating and translating x/y.\n let coordX = (x - centerX) * cosFactor - (y - centerY) * sinFactor;\n let coordY = (x - centerX) * sinFactor + (y - centerY) * cosFactor;\n coordX = Math.round(coordX + centerX);\n coordY = Math.round(coordY + centerY);\n\n let outputValue = fillValue;\n if (typeof fillValue !== 'number') {\n if (channel === 3) {\n outputValue = fullOpacityValue;\n } else {\n outputValue = fillValue[channel];\n }\n }\n\n // If the coordinate position falls within the image boundaries...\n if (coordX >= 0 && coordX < imageWidth && coordY >= 0 &&\n coordY < imageHeight) {\n // set the output to the image value at the coordinate position.\n const rotatedRowOffset = coordY * (imageWidth * numChannels);\n const rotatedColOffset = coordX * numChannels;\n const imageIdx =\n batchOffset + rotatedRowOffset + rotatedColOffset + channel;\n outputValue = imageVals[imageIdx];\n }\n\n const outIdx = batchOffset + rowOffset + colOffset + channel;\n output[outIdx] = outputValue as number;\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(output, image.shape, image.dtype);\n return {dataId, shape: image.shape, dtype: image.dtype};\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Round} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const round = unaryKernelFunc(Round, (xi) => {\n // The algorithm is based on banker's rounding.\n const base = Math.floor(xi);\n if (xi - base < 0.5) {\n return Math.floor(xi);\n } else if (xi - base > 0.5) {\n return Math.ceil(xi);\n } else {\n if (base % 2.0 === 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n});\n\nexport const roundConfig: KernelConfig = {\n kernelName: Round,\n backendName: 'cpu',\n kernelFunc: round,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Rank, ScatterNd, ScatterNdAttrs, ScatterNdInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {scatterImpl} from './Scatter_impl';\n\nexport function scatterNd(args: {\n inputs: ScatterNdInputs,\n backend: MathBackendCPU,\n attrs: ScatterNdAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {indices, updates} = inputs;\n const {shape} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(updates, indices, shape);\n const sumDupeIndices = true;\n\n const indicesBuf = backend.bufferSync(indices);\n const updatesBuf = backend.bufferSync(updates);\n\n const outBuf = scatterImpl(\n indicesBuf, updatesBuf, shape, outputSize, sliceSize, numUpdates,\n sliceRank, strides, 0 /* defaultValue */, sumDupeIndices);\n\n return backend.makeTensorInfo(shape, outBuf.dtype, outBuf.values);\n}\n\nexport const scatterNdConfig: KernelConfig = {\n kernelName: ScatterNd,\n backendName: 'cpu',\n kernelFunc: scatterNd as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray, util} from '@tensorflow/tfjs-core';\n\nfunction lowerBound(array: TypedArray, value: number) {\n let left = 0;\n let right = array.length;\n let mid = 0;\n while (left < right) {\n mid = Math.floor((left + right) / 2);\n if (array[mid] < value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n}\n\nfunction upperBound(array: TypedArray, value: number) {\n let left = 0;\n let right = array.length;\n let mid = 0;\n while (left < right) {\n mid = Math.floor((left + right) / 2);\n if (array[mid] <= value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n}\n\nexport function searchSortedImpl(\n sortedInputs: TypedArray, values: TypedArray, batchSize: number,\n numInputs: number, numValues: number, side: 'left'|'right'): TypedArray {\n const output =\n util.getArrayFromDType('int32', batchSize * numValues) as TypedArray;\n for (let b = 0; b < batchSize; ++b) {\n const sortedInputsSlice =\n sortedInputs.slice(b * numInputs, (b + 1) * numInputs);\n const outputOffset = b * numValues;\n for (let i = 0; i < numValues; ++i) {\n output[outputOffset + i] = side === 'left' ?\n lowerBound(sortedInputsSlice, values[i + outputOffset]) :\n upperBound(sortedInputsSlice, values[i + outputOffset]);\n }\n }\n return output;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SearchSorted, SearchSortedAttrs, SearchSortedInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {searchSortedImpl} from './SearchSorted_impl';\n\nexport function searchSorted(args: {\n inputs: SearchSortedInputs,\n backend: MathBackendCPU,\n attrs: SearchSortedAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {sortedSequence, values} = inputs;\n const {side} = attrs;\n\n const $sortedSequence =\n backend.data.get(sortedSequence.dataId).values as TypedArray;\n const $values = backend.data.get(values.dataId).values as TypedArray;\n\n const output = searchSortedImpl(\n $sortedSequence, $values, sortedSequence.shape[0],\n sortedSequence.shape[1], values.shape[1], side);\n return backend.makeTensorInfo(values.shape, 'int32', output);\n}\n\nexport const searchSortedConfig: KernelConfig = {\n kernelName: SearchSorted,\n backendName: 'cpu',\n kernelFunc: searchSorted as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Select, SelectInputs, TensorInfo, TypedArray, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function select(args: {inputs: SelectInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {condition, t, e} = inputs;\n\n assertNotComplex([condition, t, e], 'select');\n const conditionRank = condition.shape.length;\n\n const values = backend.data.get(condition.dataId).values as TypedArray;\n const tValues = backend.data.get(t.dataId).values as TypedArray;\n const eValues = backend.data.get(e.dataId).values as TypedArray;\n const resultDtype = upcastType(t.dtype, e.dtype);\n const newValues =\n util.makeZerosTypedArray(util.sizeFromShape(t.shape), resultDtype);\n\n let index = 0;\n const offset =\n conditionRank === 0 || conditionRank > 1 || t.shape.length === 1 ?\n 1 :\n util.sizeFromShape(t.shape.slice(1));\n\n for (let i = 0; i < values.length; i++) {\n for (let j = 0; j < offset; j++) {\n if (values[i] === 1) {\n newValues[index++] = tValues[i];\n } else {\n newValues[index++] = eValues[i];\n }\n }\n }\n\n return backend.makeTensorInfo(t.shape, resultDtype, newValues);\n}\n\nexport const selectConfig: KernelConfig = {\n kernelName: Select,\n backendName: 'cpu',\n kernelFunc: select as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, Selu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nconst scaleAlpha = backend_util.SELU_SCALEALPHA;\nconst scale = backend_util.SELU_SCALE;\n\nexport const selu = unaryKernelFunc(Selu, (xi) => {\n if (xi >= 0) {\n return scale * xi;\n } else {\n return scaleAlpha * (Math.exp(xi) - 1);\n }\n});\n\nexport const seluConfig: KernelConfig = {\n kernelName: Selu,\n backendName: 'cpu',\n kernelFunc: selu,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sign} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sign = unaryKernelFunc(Sign, (xi) => {\n if (xi < 0) {\n return -1;\n } else if (xi > 0) {\n return 1;\n } else {\n return 0;\n }\n});\n\nexport const signConfig: KernelConfig = {\n kernelName: Sign,\n backendName: 'cpu',\n kernelFunc: sign,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sin} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sin = unaryKernelFunc(Sin, (xi) => Math.sin(xi));\n\nexport const sinConfig: KernelConfig = {\n kernelName: Sin,\n backendName: 'cpu',\n kernelFunc: sin,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sinh} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sinh = unaryKernelFunc(Sinh, (xi) => Math.sinh(xi));\n\nexport const sinhConfig: KernelConfig = {\n kernelName: Sinh,\n backendName: 'cpu',\n kernelFunc: sinh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Softplus} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\n// mirrors the implementation of tf.nn.softplus: https://goo.gl/vkcvwX\n\n// epsilon is the difference between 1.0 and the next representable float.\n// For a single precision 32 bit float this should be 2^-23, see:\n// https://math.byu.edu/~schow/work/IEEEFloatingPoint.htm\nconst epsilon = 1.1920928955078125e-7;\nconst threshold = Math.log(epsilon) + 2.0;\n\nexport const softplus = unaryKernelFunc(Softplus, (xi) => {\n // Value above which exp(x) may overflow, but softplus(x) == x\n // is within machine epsilon.\n const tooLarge = xi > -threshold;\n\n // Value below which exp(x) may underflow, but softplus(x) == exp(x)\n // is within machine epsilon.\n const tooSmall = xi < threshold;\n\n const expX = Math.exp(xi);\n let result;\n\n if (tooSmall) {\n result = expX;\n } else if (tooLarge) {\n result = xi;\n } else {\n result = Math.log(1.0 + expX);\n }\n return result;\n});\n\nexport const softplusConfig: KernelConfig = {\n kernelName: Softplus,\n backendName: 'cpu',\n kernelFunc: softplus,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, ReshapeAttrs, ReshapeInputs, SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs, TensorInfo, TransposeAttrs, TransposeInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {padV2Config} from './PadV2';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function spaceToBatchND(args: {\n inputs: SpaceToBatchNDInputs,\n backend: MathBackendCPU,\n attrs: SpaceToBatchNDAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, paddings} = attrs;\n\n assertNotComplex([x], 'spaceToBatchND');\n\n const prod = util.sizeFromShape(blockShape);\n\n const completePaddings: Array<[number, number]> = [[0, 0]];\n completePaddings.push(...(paddings as Array<[number, number]>));\n\n for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {\n completePaddings.push([0, 0]);\n }\n\n const paddedX = padV2Config.kernelFunc({\n inputs: {x},\n backend,\n attrs: {paddings: completePaddings, constantValue: 0}\n }) as TensorInfo;\n\n const reshapedPaddedShape =\n backend_util.getReshaped(paddedX.shape, blockShape, prod, false);\n\n const permutedReshapedPaddedPermutation = backend_util.getPermuted(\n reshapedPaddedShape.length, blockShape.length, false);\n\n const flattenShape =\n backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod, false);\n\n const reshapeInputs: ReshapeInputs = {x: paddedX};\n const reshapeAttrs: ReshapeAttrs = {shape: reshapedPaddedShape};\n const paddedXReshaped =\n reshape({inputs: reshapeInputs, backend, attrs: reshapeAttrs});\n\n const transposeInputs: TransposeInputs = {x: paddedXReshaped};\n const transposeAttrs:\n TransposeAttrs = {perm: permutedReshapedPaddedPermutation};\n const paddedXT =\n transpose({inputs: transposeInputs, backend, attrs: transposeAttrs});\n\n const resultReshapeInputs: ReshapeInputs = {x: paddedXT};\n const resultReshapeAttrs: ReshapeAttrs = {shape: flattenShape};\n const result = reshape(\n {inputs: resultReshapeInputs, backend, attrs: resultReshapeAttrs});\n\n backend.disposeIntermediateTensorInfo(paddedX);\n backend.disposeIntermediateTensorInfo(paddedXReshaped);\n backend.disposeIntermediateTensorInfo(paddedXT);\n\n return result;\n}\n\nexport const spaceToBatchNDConfig: KernelConfig = {\n kernelName: SpaceToBatchND,\n backendName: 'cpu',\n kernelFunc: spaceToBatchND as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SparseFillEmptyRows, SparseFillEmptyRowsInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseFillEmptyRowsImpl} from './SparseFillEmptyRows_impl';\n\nexport function sparseFillEmptyRows(args: {\n inputs: SparseFillEmptyRowsInputs,\n backend: MathBackendCPU\n}): [TensorInfo, TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {indices, values, denseShape, defaultValue} = inputs;\n if (denseShape.shape.length !== 1) {\n throw new Error(`Dense shape must be a vector, saw:\n ${denseShape.shape}`);\n }\n if (indices.shape.length !== 2) {\n throw new Error(`Indices must be a matrix, saw:\n ${indices.shape}`);\n }\n if (values.shape.length !== 1) {\n throw new Error(`Values must be a vector, saw:\n ${values.shape}`);\n }\n if (defaultValue.shape.length !== 0) {\n throw new Error(`Default value must be a scalar, saw:\n ${defaultValue.shape}`);\n }\n\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n const $values = backend.data.get(values.dataId).values as TypedArray;\n const $denseShape = backend.data.get(denseShape.dataId).values as TypedArray;\n const $defaultValue =\n backend.data.get(defaultValue.dataId).values[0] as number;\n\n const [outputIndices, outputIndicesShape, outputValues,\n emptyRowIndicator, reverseIndexMap] =\n sparseFillEmptyRowsImpl(\n $indices, indices.shape, indices.dtype, $values, values.dtype,\n $denseShape, $defaultValue);\n return [\n backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),\n backend.makeTensorInfo(\n [outputIndicesShape[0]], values.dtype, outputValues),\n backend.makeTensorInfo(\n [emptyRowIndicator.length], 'bool',\n new Uint8Array(\n emptyRowIndicator.map((value: boolean) => Number(value)))),\n backend.makeTensorInfo(\n [reverseIndexMap.length], indices.dtype,\n new Int32Array(reverseIndexMap)),\n ];\n}\n\nexport const sparseFillEmptyRowsConfig: KernelConfig = {\n kernelName: SparseFillEmptyRows,\n backendName: 'cpu',\n kernelFunc: sparseFillEmptyRows as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SparseReshape, SparseReshapeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseReshapeImpl} from './SparseReshape_impl';\n\nexport function sparseReshape(\n args: {inputs: SparseReshapeInputs, backend: MathBackendCPU}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {inputIndices, inputShape, newShape} = inputs;\n if (inputIndices.shape.length !== 2) {\n throw new Error(`Input indices should be a matrix but received shape\n ${inputIndices.shape}`);\n }\n if (inputShape.shape.length !== 1) {\n throw new Error(`Input shape should be a vector but received shape\n ${inputShape.shape}`);\n }\n\n if (newShape.shape.length !== 1) {\n throw new Error(\n `Target shape should be a vector but received shape ${newShape.shape}`);\n }\n\n const $inputShape =\n Array.from(backend.data.get(inputShape.dataId).values as TypedArray);\n const $inputIndices =\n backend.data.get(inputIndices.dataId).values as TypedArray;\n const targetShape =\n Array.from(backend.data.get(newShape.dataId).values as TypedArray);\n\n const [newIndices, indicesShape, outputShape] = sparseReshapeImpl(\n $inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape,\n targetShape);\n return [\n backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),\n backend.makeTensorInfo(\n [outputShape.length], newShape.dtype, new Int32Array(outputShape)),\n ];\n}\n\nexport const sparseReshapeConfig: KernelConfig = {\n kernelName: SparseReshape,\n backendName: 'cpu',\n kernelFunc: sparseReshape,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SparseSegmentMean, SparseSegmentMeanInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseSegmentReductionImpl} from './SparseSegmentReduction_impl';\n\nexport function sparseSegmentMean(\n args: {inputs: SparseSegmentMeanInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n if (indices.shape[0] !== segmentIds.shape[0]) {\n throw new Error(`segmentIds and indices should have same size.`);\n }\n\n const $data = backend.data.get(data.dataId).values as TypedArray;\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n const $segmentIds = backend.data.get(segmentIds.dataId).values as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImpl(\n $data, data.shape, data.dtype, $indices, $segmentIds, true);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentMeanConfig: KernelConfig = {\n kernelName: SparseSegmentMean,\n backendName: 'cpu',\n kernelFunc: sparseSegmentMean,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SparseSegmentSum, SparseSegmentSumInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseSegmentReductionImpl} from './SparseSegmentReduction_impl';\n\nexport function sparseSegmentSum(\n args: {inputs: SparseSegmentSumInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n if (indices.shape[0] !== segmentIds.shape[0]) {\n throw new Error(`segmentIds and indices should have same size.`);\n }\n\n const $data = backend.data.get(data.dataId).values as TypedArray;\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n const $segmentIds = backend.data.get(segmentIds.dataId).values as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImpl(\n $data, data.shape, data.dtype, $indices, $segmentIds);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentSumConfig: KernelConfig = {\n kernelName: SparseSegmentSum,\n backendName: 'cpu',\n kernelFunc: sparseSegmentSum,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Rank, SparseToDense, SparseToDenseAttrs, SparseToDenseInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {scatterImpl} from './Scatter_impl';\n\nexport function sparseToDense(args: {\n inputs: SparseToDenseInputs,\n backend: MathBackendCPU,\n attrs: SparseToDenseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {sparseIndices, sparseValues, defaultValue} = inputs;\n const {outputShape} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(sparseValues, sparseIndices, outputShape);\n const sumDupeIndices = false;\n\n const indicesBuf = backend.bufferSync(sparseIndices);\n\n let outBuf;\n switch (sparseValues.dtype) {\n case 'bool': {\n const updatesBuf = backend.bufferSync(sparseValues);\n const $defaultValue =\n Boolean(backend.data.get(defaultValue.dataId).values[0]);\n outBuf = scatterImpl(\n indicesBuf, updatesBuf, outputShape, outputSize, sliceSize,\n numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);\n break;\n }\n case 'float32': {\n const updatesBuf = backend.bufferSync(sparseValues);\n const $defaultValue =\n backend.data.get(defaultValue.dataId).values[0] as number;\n outBuf = scatterImpl(\n indicesBuf, updatesBuf, outputShape, outputSize, sliceSize,\n numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);\n break;\n }\n case 'int32': {\n const updatesBuf = backend.bufferSync(sparseValues);\n const $defaultValue =\n backend.data.get(defaultValue.dataId).values[0] as number;\n outBuf = scatterImpl(\n indicesBuf, updatesBuf, outputShape, outputSize, sliceSize,\n numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);\n break;\n }\n case 'string': {\n const updatesBuf = backend.bufferSync(sparseValues);\n const $defaultValue = util.decodeString(\n backend.data.get(defaultValue.dataId).values[0] as Uint8Array);\n outBuf = scatterImpl(\n indicesBuf, updatesBuf, outputShape, outputSize, sliceSize,\n numUpdates, sliceRank, strides, $defaultValue, sumDupeIndices);\n break;\n }\n default:\n throw new Error(`Unsupported type ${sparseValues.dtype}`);\n }\n return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);\n}\n\nexport const sparseToDenseConfig: KernelConfig = {\n kernelName: SparseToDense,\n backendName: 'cpu',\n kernelFunc: sparseToDense as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, SplitVAttrs, SplitVInputs} from '@tensorflow/tfjs-core';\nimport {KernelConfig, KernelFunc, SplitV, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {slice} from './Slice';\n\nexport function splitV(\n args: {inputs: SplitVInputs, backend: MathBackendCPU, attrs: SplitVAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {numOrSizeSplits, axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, x.shape)[0];\n const splitSizes = backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);\n\n const begin = new Array(x.shape.length).fill(0);\n const size = x.shape.slice();\n return splitSizes.map(s => {\n const sliceSize = [...size];\n sliceSize[$axis] = s;\n const sliceT =\n slice({inputs: {x}, backend, attrs: {begin, size: sliceSize}});\n begin[$axis] += s;\n return sliceT;\n });\n}\n\nexport const splitVConfig: KernelConfig = {\n kernelName: SplitV,\n backendName: 'cpu',\n kernelFunc: splitV as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Square, SquareInputs} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport const squareConfig: KernelConfig = {\n kernelName: Square,\n backendName: 'cpu',\n kernelFunc: ({inputs, backend}) => {\n const {x} = inputs as SquareInputs;\n const cpuBackend = backend as MathBackendCPU;\n assertNotComplex(x, 'square');\n\n const values = cpuBackend.data.get(x.dataId).values as Float32Array;\n const newValues = new Float32Array(values.length);\n for (let i = 0; i < values.length; ++i) {\n const value = values[i];\n newValues[i] = value * value;\n }\n const dataId = cpuBackend.write(newValues, x.shape, x.dtype);\n return {dataId, shape: x.shape, dtype: x.dtype};\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Step, StepAttrs} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const step = unaryKernelFunc(Step, (xi, attrs) => {\n const stepAttrs = attrs as unknown as StepAttrs;\n if (isNaN(xi)) {\n return NaN;\n } else {\n return xi > 0 ? 1 : stepAttrs.alpha;\n }\n});\n\nexport const stepConfig: KernelConfig = {\n kernelName: Step,\n backendName: 'cpu',\n kernelFunc: step,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Rank, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {stridedSliceImpl} from './StridedSlice_impl';\n\nexport function stridedSlice(args: {\n inputs: StridedSliceInputs,\n backend: MathBackendCPU,\n attrs: StridedSliceAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {\n begin,\n end,\n strides,\n beginMask,\n endMask,\n ellipsisMask,\n newAxisMask,\n shrinkAxisMask\n } = attrs;\n\n assertNotComplex(x, 'stridedSlice');\n\n const {\n finalShapeSparse,\n finalShape,\n isIdentity,\n sliceDim0,\n isSimpleSlice,\n begin: $begin,\n end: $end,\n strides: $strides\n } =\n slice_util.sliceInfo(\n x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask);\n\n let result;\n\n // ref:\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/strided_slice_op.cc\n if (isIdentity) {\n // Optimization #1, slice is a no-op plus reshape\n result = reshape({inputs: {x}, backend, attrs: {shape: finalShape}});\n } else if (sliceDim0 || isSimpleSlice) {\n // Optimization #2, slice is memory contiguous (only occurs in dim 0)\n util.assert(\n x.shape.length >= 1,\n () => `Input must have rank at least 1, got: ${x.shape.length}`);\n\n const size = slice_util.computeOutShape($begin, $end, $strides);\n // To tolerate begin[0] > end[0] (a 0-output slice), we min(begin, end).\n const sliced = slice({inputs: {x}, backend, attrs: {begin: $begin, size}});\n result =\n reshape({inputs: {x: sliced}, backend, attrs: {shape: finalShape}});\n backend.disposeIntermediateTensorInfo(sliced);\n } else {\n const xBuf = backend.bufferSync(x);\n const outBuf = stridedSliceImpl(finalShapeSparse, xBuf, $strides, $begin);\n\n result = backend.makeTensorInfo(finalShape, outBuf.dtype, outBuf.values);\n }\n\n return result;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n kernelName: StridedSlice,\n backendName: 'cpu',\n kernelFunc: stridedSlice as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringNGrams, StringNGramsAttrs, StringNGramsInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {stringNGramsImpl} from './StringNGrams_impl';\n\nexport function stringNGrams(args: {\n inputs: StringNGramsInputs,\n backend: MathBackendCPU,\n attrs: StringNGramsAttrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {\n separator,\n nGramWidths,\n leftPad,\n rightPad,\n padWidth,\n preserveShortSequences\n } = attrs;\n const {data, dataSplits} = inputs;\n const $data = backend.data.get(data.dataId).values as Uint8Array[];\n const $dataSplits = backend.data.get(dataSplits.dataId).values as Int32Array;\n\n const [nGrams, nGramsSplits] = stringNGramsImpl(\n $data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences);\n return [\n backend.makeTensorInfo([nGrams.length], 'string', nGrams),\n backend.makeTensorInfo(dataSplits.shape, 'int32', nGramsSplits),\n ];\n}\n\nexport const stringNGramsConfig: KernelConfig = {\n kernelName: StringNGrams,\n backendName: 'cpu',\n kernelFunc: stringNGrams as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringSplit, StringSplitAttrs, StringSplitInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {stringSplitImpl} from './StringSplit_impl';\n\nexport function stringSplit(args: {\n inputs: StringSplitInputs,\n backend: MathBackendCPU,\n attrs: StringSplitAttrs\n}): [TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {skipEmpty} = attrs;\n const {input, delimiter} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (input.shape.length !== 1) {\n throw new Error(`Input must be a vector, got shape: ${input.shape}`);\n }\n if (delimiter.shape.length !== 0) {\n throw new Error(\n `Delimiter must be a scalar, got shape: ${delimiter.shape}`);\n }\n\n const $input = backend.data.get(input.dataId).values as Uint8Array[];\n const $delimiter = backend.data.get(delimiter.dataId).values[0] as Uint8Array;\n\n const [indices, values, shape] =\n stringSplitImpl($input, $delimiter, skipEmpty);\n const outputSize = values.length;\n return [\n backend.makeTensorInfo([outputSize, 2], 'int32', indices),\n backend.makeTensorInfo([outputSize], 'string', values),\n backend.makeTensorInfo([2], 'int32', new Int32Array(shape))\n ];\n}\n\nexport const stringSplitConfig: KernelConfig = {\n kernelName: StringSplit,\n backendName: 'cpu',\n kernelFunc: stringSplit as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {stringToHashBucketFastImpl} from './StringToHashBucketFast_impl';\n\nexport function stringToHashBucketFast(args: {\n inputs: StringToHashBucketFastInputs,\n backend: MathBackendCPU,\n attrs: StringToHashBucketFastAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {numBuckets} = attrs;\n const {input} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (numBuckets <= 0) {\n throw new Error(`Number of buckets must be at least 1`);\n }\n\n const $input = backend.data.get(input.dataId).values as Uint8Array[];\n\n const output = stringToHashBucketFastImpl($input, numBuckets);\n return backend.makeTensorInfo(input.shape, 'int32', output);\n}\n\nexport const stringToHashBucketFastConfig: KernelConfig = {\n kernelName: StringToHashBucketFast,\n backendName: 'cpu',\n kernelFunc: stringToHashBucketFast as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Tan} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const tan = unaryKernelFunc(Tan, (xi) => Math.tan(xi));\n\nexport const tanConfig: KernelConfig = {\n kernelName: Tan,\n backendName: 'cpu',\n kernelFunc: tan,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Tanh} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const tanh = unaryKernelFunc(Tanh, (xi) => Math.tanh(xi));\n\nexport const tanhConfig: KernelConfig = {\n kernelName: Tanh,\n backendName: 'cpu',\n kernelFunc: tanh,\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Rank, TensorInfo, TensorScatterUpdate, TensorScatterUpdateAttrs, TensorScatterUpdateInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {scatterImpl} from './Scatter_impl';\n\nexport function tensorScatterUpdate(args: {\n inputs: TensorScatterUpdateInputs,\n backend: MathBackendCPU,\n attrs: TensorScatterUpdateAttrs\n}): TensorInfo {\n const {inputs, backend} = args;\n const {tensor, indices, updates} = inputs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(updates, indices, tensor.shape);\n const sumDupeIndices = false;\n\n const indicesBuf = backend.bufferSync(indices);\n const updatesBuf = backend.bufferSync(updates);\n const tensorBuf = backend.bufferSync(tensor);\n const outBuf = scatterImpl(\n indicesBuf, updatesBuf, tensor.shape, outputSize, sliceSize, numUpdates,\n sliceRank, strides, tensorBuf, sumDupeIndices);\n return backend.makeTensorInfo(tensor.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const tensorScatterUpdateConfig: KernelConfig = {\n kernelName: TensorScatterUpdate,\n backendName: 'cpu',\n kernelFunc: tensorScatterUpdate as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Tile, TileAttrs, TileInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {tileImpl} from './Tile_impl';\n\nexport function tile(\n args: {inputs: TileInputs, backend: MathBackendCPU, attrs: TileAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {reps} = attrs;\n\n assertNotComplex(x, 'tile');\n const outBuf = tileImpl(backend.bufferSync(x), reps);\n\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const tileConfig: KernelConfig = {\n kernelName: Tile,\n backendName: 'cpu',\n kernelFunc: tile as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, NumericDataType, TensorInfo, TopK, TopKAttrs, TopKInputs, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {topKImpl} from './TopK_impl';\n\nexport function topK(\n args: {inputs: TopKInputs, backend: MathBackendCPU, attrs: TopKAttrs}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {k, sorted} = attrs;\n\n assertNotComplex(x, 'topk');\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const [allTopKVals, allTopKIndices] =\n topKImpl(xVals, x.shape, x.dtype as NumericDataType, k, sorted);\n\n return [\n backend.makeTensorInfo(\n allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),\n backend.makeTensorInfo(\n allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)\n ];\n}\n\nexport const topKConfig: KernelConfig = {\n kernelName: TopK,\n backendName: 'cpu',\n kernelFunc: topK as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, NumericDataType, TensorInfo, Transform, TransformAttrs, TransformInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function transform(args: {\n inputs: TransformInputs,\n attrs: TransformAttrs,\n backend: MathBackendCPU\n}): TensorInfo {\n const {inputs, attrs, backend} = args;\n const {image, transforms} = inputs;\n const {interpolation, fillMode, fillValue, outputShape} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const [outHeight, outWidth] =\n outputShape != null ? outputShape : [imageHeight, imageWidth];\n const outShape = [batch, outHeight, outWidth, numChannels];\n\n const inStrides = util.computeStrides(image.shape);\n const batchInStride = inStrides[0];\n const rowInStride = inStrides[1];\n const colInStride = inStrides[2];\n\n const outStrides = util.computeStrides(outShape);\n const batchOutStride = outStrides[0];\n const rowOutStride = outStrides[1];\n const colOutStride = outStrides[2];\n\n const outVals = util.getTypedArrayFromDType(\n image.dtype as NumericDataType, util.sizeFromShape(outShape));\n\n outVals.fill(fillValue);\n\n const imageVals = backend.data.get(image.dataId).values as TypedArray;\n const transformVals =\n backend.data.get(transforms.dataId).values as TypedArray;\n\n // Ref TF implementation:\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/image/image_ops.h\n for (let b = 0; b < batch; ++b) {\n const transform = transforms.shape[0] === 1 ?\n transformVals :\n transformVals.subarray(b * 8, b * 8 + 8);\n\n for (let outY = 0; outY < outHeight; ++outY) {\n for (let outX = 0; outX < outWidth; ++outX) {\n for (let channel = 0; channel < numChannels; ++channel) {\n let val;\n\n const projection = transform[6] * outX + transform[7] * outY + 1;\n\n if (projection === 0) {\n // Return the fill value for infinite coordinates,\n // which are outside the input image\n continue;\n }\n\n const inX =\n (transform[0] * outX + transform[1] * outY + transform[2]) /\n projection;\n const inY =\n (transform[3] * outX + transform[4] * outY + transform[5]) /\n projection;\n\n const x = mapCoord(inX, imageWidth, fillMode);\n const y = mapCoord(inY, imageHeight, fillMode);\n\n switch (interpolation) {\n case 'nearest':\n val = nearestInterpolation(\n imageVals, imageHeight, imageWidth, batchInStride,\n rowInStride, colInStride, b, y, x, channel, fillValue);\n break;\n case 'bilinear':\n val = bilinearInterpolation(\n imageVals, imageHeight, imageWidth, batchInStride,\n rowInStride, colInStride, b, y, x, channel, fillValue);\n break;\n default:\n throw new Error(\n `Error in Transform: Expect 'nearest' or ` +\n `'bilinear', but got ${interpolation}`);\n }\n\n const ind =\n b * batchOutStride + outY * rowOutStride +\n outX * colOutStride + channel;\n\n outVals[ind] = val;\n }\n }\n }\n\n return backend.makeTensorInfo(outShape, image.dtype, outVals);\n }\n\n const dataId = backend.write(outVals, outShape, image.dtype);\n return {dataId, shape: image.shape, dtype: image.dtype};\n}\n\nexport const transformConfig: KernelConfig = {\n kernelName: Transform,\n backendName: 'cpu',\n kernelFunc: transform as unknown as KernelFunc\n};\n\nfunction mapCoord(\n outCoord: number, len: number,\n mode: 'constant'|'reflect'|'wrap'|'nearest') {\n switch (mode) {\n case 'reflect':\n return mapCoordReflect(outCoord, len);\n case 'wrap':\n return mapCoordWrap(outCoord, len);\n case 'nearest':\n return mapCoordNearest(outCoord, len);\n case 'constant':\n default:\n return mapCoordConstant(outCoord, len);\n }\n}\n\nfunction mapCoordReflect(outCoord: number, len: number): number {\n // Reflect [abcd] to [dcba|abcd|dcba].\n let inCoord = outCoord;\n if (inCoord < 0) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz2 = 2 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * Math.trunc(-inCoord / sz2) + inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1;\n }\n } else if (inCoord > len - 1) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz2 = 2 * len;\n inCoord -= sz2 * Math.trunc(inCoord / sz2);\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1;\n }\n }\n }\n // clamp is necessary because when outCoord = 3.5 and len = 4,\n // inCoord = 3.5 and will be rounded to 4 in nearest interpolation.\n return util.clamp(0, inCoord, len - 1);\n}\n\nfunction mapCoordWrap(outCoord: number, len: number): number {\n // Wrap [abcd] to [abcd|abcd|abcd].\n let inCoord = outCoord;\n if (inCoord < 0) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz = len - 1;\n inCoord += len * (Math.trunc(-inCoord / sz) + 1);\n }\n } else if (inCoord > len - 1) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz = len - 1;\n inCoord -= len * Math.trunc(inCoord / sz);\n }\n }\n // clamp is necessary because when outCoord = -0.5 and len = 4,\n // inCoord = 3.5 and will be rounded to 4 in nearest interpolation.\n return util.clamp(0, inCoord, len - 1);\n}\n\nfunction mapCoordConstant(outCoord: number, len: number): number {\n return outCoord;\n}\n\nfunction mapCoordNearest(outCoord: number, len: number): number {\n return util.clamp(0, outCoord, len - 1);\n}\n\nfunction readWithFillValue(\n imageVals: TypedArray, imageHeight: number, imageWidth: number,\n batchStride: number, rowStride: number, colStride: number, batch: number,\n y: number, x: number, channel: number, fillValue: number): number {\n const ind = batch * batchStride + y * rowStride + x * colStride + channel;\n if (0 <= y && y < imageHeight && 0 <= x && x < imageWidth) {\n return imageVals[ind];\n } else {\n return fillValue;\n }\n}\n\nfunction nearestInterpolation(\n imageVals: TypedArray, imageHeight: number, imageWidth: number,\n batchStride: number, rowStride: number, colStride: number, batch: number,\n y: number, x: number, channel: number, fillValue: number): number {\n const $y = Math.round(y);\n const $x = Math.round(x);\n\n return readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride,\n batch, $y, $x, channel, fillValue);\n}\n\nfunction bilinearInterpolation(\n imageVals: TypedArray, imageHeight: number, imageWidth: number,\n batchStride: number, rowStride: number, colStride: number, batch: number,\n y: number, x: number, channel: number, fillValue: number) {\n const yFloor = Math.floor(y);\n const xFloor = Math.floor(x);\n const yCeil = yFloor + 1;\n const xCeil = xFloor + 1;\n // f(x, yFloor) = (xCeil - x) / (xCeil - xFloor) * f(xFloor, yFloor)\n // + (x - xFloor) / (xCeil - xFloor) * f(xCeil, yFloor)\n const valueYFloor =\n (xCeil - x) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yFloor, xFloor, channel, fillValue) +\n (x - xFloor) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yFloor, xCeil, channel, fillValue);\n // f(x, yCeil) = (xCeil - x) / (xCeil - xFloor) * f(xFloor, yCeil)\n // + (x - xFloor) / (xCeil - xFloor) * f(xCeil, yCeil)\n const valueYCeil =\n (xCeil - x) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yCeil, xFloor, channel, fillValue) +\n (x - xFloor) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yCeil, xCeil, channel, fillValue);\n // f(x, y) = (yCeil - y) / (yCeil - yFloor) * f(x, yFloor)\n // + (y - yFloor) / (yCeil - yFloor) * f(x, yCeil)\n return (yCeil - y) * valueYFloor + (y - yFloor) * valueYCeil;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Unique, UniqueAttrs, UniqueInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {uniqueImpl} from './Unique_impl';\n\nexport function unique(\n args: {inputs: UniqueInputs, attrs: UniqueAttrs, backend: MathBackendCPU}):\n TensorInfo[] {\n const {inputs, attrs, backend} = args;\n const {axis} = attrs;\n const {x} = inputs;\n assertNotComplex(x, 'unique');\n\n const values = backend.data.get(x.dataId).values;\n const {outputValues, outputShape, indices} =\n uniqueImpl(values, axis, x.shape, x.dtype);\n return [\n backend.makeTensorInfo(outputShape, x.dtype, outputValues),\n backend.makeTensorInfo([indices.length], 'int32', indices),\n ];\n}\n\nexport const uniqueConfig: KernelConfig = {\n kernelName: Unique,\n backendName: 'cpu',\n kernelFunc: unique as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Unpack, UnpackAttrs, UnpackInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nexport function unpack(\n args: {inputs: UnpackInputs, backend: MathBackendCPU, attrs: UnpackAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {value} = inputs;\n let {axis} = attrs;\n\n if (axis < 0) {\n axis += value.shape.length;\n }\n\n const valueRank = value.shape.length;\n\n const num = value.shape[axis];\n const outShape: number[] = new Array(valueRank - 1);\n let outIndex = 0;\n for (let i = 0; i < valueRank; i++) {\n if (i !== axis) {\n outShape[outIndex++] = value.shape[i];\n }\n }\n\n const begin = new Array(valueRank).fill(0);\n const size = value.shape.slice();\n size[axis] = 1;\n const res = new Array(num);\n for (let i = 0; i < res.length; i++) {\n begin[axis] = i;\n const tempRes = slice({inputs: {x: value}, backend, attrs: {begin, size}});\n res[i] = reshape({inputs: {x: tempRes}, backend, attrs: {shape: outShape}});\n backend.disposeIntermediateTensorInfo(tempRes);\n }\n\n return res;\n}\n\nexport const unpackConfig: KernelConfig = {\n kernelName: Unpack,\n backendName: 'cpu',\n kernelFunc: unpack as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {cast} from './Cast';\nimport {equal} from './Equal';\nimport {expandDims} from './ExpandDims';\nimport {multiply} from './Multiply';\nimport {pack} from './Pack';\nimport {sum} from './Sum';\n\nexport function unsortedSegmentSum(args: {\n inputs: UnsortedSegmentSumInputs,\n backend: MathBackendCPU,\n attrs: UnsortedSegmentSumAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, segmentIds} = inputs;\n const {numSegments} = attrs;\n\n assertNotComplex(x, 'unsortedSegmentSum');\n\n const xRank = x.shape.length;\n const segmentIdsRank = segmentIds.shape.length;\n const res = [];\n const intermediates: TensorInfo[] = [];\n\n // Reshape the segment id's so that they can be broadcast with\n // x. The new shape should be [segmentIds.shape, 1, ..., 1]\n const numIters = xRank - segmentIdsRank;\n let $segmentIds = segmentIds;\n\n for (let i = 0; i < numIters; ++i) {\n const expanded = expandDims(\n {inputs: {input: $segmentIds}, backend, attrs: {dim: i + 1}});\n $segmentIds = expanded;\n intermediates.push(expanded);\n }\n\n for (let i = 0; i < numSegments; ++i) {\n const scalarValue = util.createScalarValue(\n i as unknown as 'int32', 'int32');\n const segmentId = backend.makeTensorInfo([], 'int32', scalarValue);\n const mask =\n equal({inputs: {a: segmentId, b: $segmentIds}, backend}) as TensorInfo;\n const maskCasted =\n cast({inputs: {x: mask}, backend, attrs: {dtype: 'float32'}});\n const mul =\n multiply({inputs: {a: maskCasted, b: x}, backend}) as TensorInfo;\n const sumTensorInfo =\n sum({inputs: {x: mul}, backend, attrs: {axis: 0, keepDims: false}});\n res.push(sumTensorInfo);\n intermediates.push(segmentId);\n intermediates.push(mask);\n intermediates.push(maskCasted);\n intermediates.push(mul);\n intermediates.push(sumTensorInfo);\n }\n\n const result = pack({inputs: res, backend, attrs: {axis: 0}});\n\n intermediates.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const unsortedSegmentSumConfig: KernelConfig = {\n kernelName: UnsortedSegmentSum,\n backendName: 'cpu',\n kernelFunc: unsortedSegmentSum as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// We explicitly import the modular kernels so they get registered in the\n// global registry when we compile the library. A modular build would replace\n// the contents of this file and import only the kernels that are needed.\nimport {KernelConfig, registerKernel} from '@tensorflow/tfjs-core';\n\nimport {_fusedMatMulConfig} from './kernels/_FusedMatMul';\nimport {absConfig} from './kernels/Abs';\nimport {acosConfig} from './kernels/Acos';\nimport {acoshConfig} from './kernels/Acosh';\nimport {addConfig} from './kernels/Add';\nimport {addNConfig} from './kernels/AddN';\nimport {allConfig} from './kernels/All';\nimport {anyConfig} from './kernels/Any';\nimport {argMaxConfig} from './kernels/ArgMax';\nimport {argMinConfig} from './kernels/ArgMin';\nimport {asinConfig} from './kernels/Asin';\nimport {asinhConfig} from './kernels/Asinh';\nimport {atanConfig} from './kernels/Atan';\nimport {atan2Config} from './kernels/Atan2';\nimport {atanhConfig} from './kernels/Atanh';\nimport {avgPoolConfig} from './kernels/AvgPool';\nimport {avgPool3DConfig} from './kernels/AvgPool3D';\nimport {avgPool3DGradConfig} from './kernels/AvgPool3DGrad';\nimport {avgPoolGradConfig} from './kernels/AvgPoolGrad';\nimport {batchMatMulConfig} from './kernels/BatchMatMul';\nimport {batchNormConfig} from './kernels/BatchNorm';\nimport {batchToSpaceNDConfig} from './kernels/BatchToSpaceND';\nimport {bincountConfig} from './kernels/Bincount';\nimport {bitwiseAndConfig} from './kernels/BitwiseAnd';\nimport {broadcastArgsConfig} from './kernels/BroadcastArgs';\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 {conv3DBackpropInputV2Config} from './kernels/Conv3DBackpropInputV2';\nimport {cosConfig} from './kernels/Cos';\nimport {coshConfig} from './kernels/Cosh';\nimport {cropAndResizeConfig} from './kernels/CropAndResize';\nimport {cumprodConfig} from './kernels/Cumprod';\nimport {cumsumConfig} from './kernels/Cumsum';\nimport {denseBincountConfig} from './kernels/DenseBincount';\nimport {depthToSpaceConfig} from './kernels/DepthToSpace';\nimport {depthwiseConv2dNativeConfig} from './kernels/DepthwiseConv2dNative';\nimport {depthwiseConv2dNativeBackpropFilterConfig} from './kernels/DepthwiseConv2dNativeBackpropFilter';\nimport {depthwiseConv2dNativeBackpropInputConfig} from './kernels/DepthwiseConv2dNativeBackpropInput';\nimport {diagConfig} from './kernels/Diag';\nimport {dilation2DConfig} from './kernels/Dilation2D';\nimport {dilation2DBackpropFilterConfig} from './kernels/Dilation2DBackpropFilter';\nimport {dilation2DBackpropInputConfig} from './kernels/Dilation2DBackpropInput';\nimport {drawConfig} from './kernels/Draw';\nimport {einsumConfig} from './kernels/Einsum';\nimport {eluConfig} from './kernels/Elu';\nimport {eluGradConfig} from './kernels/EluGrad';\nimport {equalConfig} from './kernels/Equal';\nimport {erfConfig} from './kernels/Erf';\nimport {expConfig} from './kernels/Exp';\nimport {expandDimsConfig} from './kernels/ExpandDims';\nimport {expm1Config} from './kernels/Expm1';\nimport {fftConfig} from './kernels/FFT';\nimport {fillConfig} from './kernels/Fill';\nimport {flipLeftRightConfig} from './kernels/FlipLeftRight';\nimport {floorConfig} from './kernels/Floor';\nimport {floorDivConfig} from './kernels/FloorDiv';\nimport {fusedConv2DConfig} from './kernels/FusedConv2D';\nimport {fusedDepthwiseConv2DConfig} from './kernels/FusedDepthwiseConv2D';\nimport {gatherNdConfig} from './kernels/GatherNd';\nimport {gatherV2Config} from './kernels/GatherV2';\nimport {greaterConfig} from './kernels/Greater';\nimport {greaterEqualConfig} from './kernels/GreaterEqual';\nimport {identityConfig} from './kernels/Identity';\nimport {ifftConfig} from './kernels/IFFT';\nimport {imagConfig} from './kernels/Imag';\nimport {isFiniteConfig} from './kernels/IsFinite';\nimport {isInfConfig} from './kernels/IsInf';\nimport {isNaNConfig} from './kernels/IsNaN';\nimport {leakyReluConfig} from './kernels/LeakyRelu';\nimport {lessConfig} from './kernels/Less';\nimport {lessEqualConfig} from './kernels/LessEqual';\nimport {linSpaceConfig} from './kernels/LinSpace';\nimport {logConfig} from './kernels/Log';\nimport {log1pConfig} from './kernels/Log1p';\nimport {logicalAndConfig} from './kernels/LogicalAnd';\nimport {logicalNotConfig} from './kernels/LogicalNot';\nimport {logicalOrConfig} from './kernels/LogicalOr';\nimport {LRNConfig} from './kernels/LRN';\nimport {LRNGradConfig} from './kernels/LRNGrad';\nimport {maxConfig} from './kernels/Max';\nimport {maximumConfig} from './kernels/Maximum';\nimport {maxPoolConfig} from './kernels/MaxPool';\nimport {maxPool3DConfig} from './kernels/MaxPool3D';\nimport {maxPool3DGradConfig} from './kernels/MaxPool3DGrad';\nimport {maxPoolGradConfig} from './kernels/MaxPoolGrad';\nimport {maxPoolWithArgmaxConfig} from './kernels/MaxPoolWithArgmax';\nimport {meanConfig} from './kernels/Mean';\nimport {minConfig} from './kernels/Min';\nimport {minimumConfig} from './kernels/Minimum';\nimport {mirrorPadConfig} from './kernels/MirrorPad';\nimport {modConfig} from './kernels/Mod';\nimport {multinomialConfig} from './kernels/Multinomial';\nimport {multiplyConfig} from './kernels/Multiply';\nimport {negConfig} from './kernels/Neg';\nimport {nonMaxSuppressionV3Config} from './kernels/NonMaxSuppressionV3';\nimport {nonMaxSuppressionV4Config} from './kernels/NonMaxSuppressionV4';\nimport {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';\nimport {notEqualConfig} from './kernels/NotEqual';\nimport {oneHotConfig} from './kernels/OneHot';\nimport {onesLikeConfig} from './kernels/OnesLike';\nimport {packConfig} from './kernels/Pack';\nimport {padV2Config} from './kernels/PadV2';\nimport {powConfig} from './kernels/Pow';\nimport {preluConfig} from './kernels/Prelu';\nimport {prodConfig} from './kernels/Prod';\nimport {raggedGatherConfig} from './kernels/RaggedGather';\nimport {raggedRangeConfig} from './kernels/RaggedRange';\nimport {raggedTensorToTensorConfig} from './kernels/RaggedTensorToTensor';\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 {searchSortedConfig} from './kernels/SearchSorted';\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 {staticRegexReplaceConfig} from './kernels/StaticRegexReplace';\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 {tensorScatterUpdateConfig} from './kernels/TensorScatterUpdate';\nimport {tileConfig} from './kernels/Tile';\nimport {topKConfig} from './kernels/TopK';\nimport {transformConfig} from './kernels/Transform';\nimport {transposeConfig} from './kernels/Transpose';\nimport {uniqueConfig} from './kernels/Unique';\nimport {unpackConfig} from './kernels/Unpack';\nimport {unsortedSegmentSumConfig} from './kernels/UnsortedSegmentSum';\nimport {zerosLikeConfig} from './kernels/ZerosLike';\n\n// List all kernel configs here\nconst kernelConfigs: KernelConfig[] = [\n _fusedMatMulConfig,\n absConfig,\n acosConfig,\n acoshConfig,\n addConfig,\n addNConfig,\n allConfig,\n anyConfig,\n argMaxConfig,\n argMinConfig,\n asinConfig,\n asinhConfig,\n atanConfig,\n atan2Config,\n atanhConfig,\n avgPoolConfig,\n avgPool3DConfig,\n avgPool3DGradConfig,\n avgPoolGradConfig,\n batchMatMulConfig,\n batchNormConfig,\n batchToSpaceNDConfig,\n bincountConfig,\n bitwiseAndConfig,\n broadcastArgsConfig,\n castConfig,\n ceilConfig,\n clipByValueConfig,\n complexConfig,\n complexAbsConfig,\n concatConfig,\n conv2DConfig,\n conv2DBackpropFilterConfig,\n conv2DBackpropInputConfig,\n conv3DConfig,\n conv3DBackpropFilterV2Config,\n conv3DBackpropInputV2Config,\n cosConfig,\n coshConfig,\n cropAndResizeConfig,\n cumprodConfig,\n cumsumConfig,\n denseBincountConfig,\n depthToSpaceConfig,\n depthwiseConv2dNativeConfig,\n depthwiseConv2dNativeBackpropFilterConfig,\n depthwiseConv2dNativeBackpropInputConfig,\n diagConfig,\n dilation2DConfig,\n dilation2DBackpropFilterConfig,\n dilation2DBackpropInputConfig,\n drawConfig,\n einsumConfig,\n eluConfig,\n eluGradConfig,\n equalConfig,\n erfConfig,\n expConfig,\n expandDimsConfig,\n expm1Config,\n fftConfig,\n fillConfig,\n flipLeftRightConfig,\n floorConfig,\n floorDivConfig,\n fusedConv2DConfig,\n fusedDepthwiseConv2DConfig,\n gatherNdConfig,\n gatherV2Config,\n greaterConfig,\n greaterEqualConfig,\n identityConfig,\n ifftConfig,\n imagConfig,\n isFiniteConfig,\n isInfConfig,\n isNaNConfig,\n leakyReluConfig,\n lessConfig,\n lessEqualConfig,\n linSpaceConfig,\n logConfig,\n log1pConfig,\n logicalAndConfig,\n logicalNotConfig,\n logicalOrConfig,\n LRNConfig,\n LRNGradConfig,\n maxConfig,\n maximumConfig,\n maxPoolConfig,\n maxPool3DConfig,\n maxPool3DGradConfig,\n maxPoolGradConfig,\n maxPoolWithArgmaxConfig,\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 raggedGatherConfig,\n raggedRangeConfig,\n raggedTensorToTensorConfig,\n rangeConfig,\n realConfig,\n realDivConfig,\n reciprocalConfig,\n reluConfig,\n relu6Config,\n reshapeConfig,\n resizeBilinearConfig,\n resizeBilinearGradConfig,\n resizeNearestNeighborConfig,\n resizeNearestNeighborGradConfig,\n reverseConfig,\n rotateWithOffsetConfig,\n roundConfig,\n rsqrtConfig,\n scatterNdConfig,\n searchSortedConfig,\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 staticRegexReplaceConfig,\n stepConfig,\n stridedSliceConfig,\n stringNGramsConfig,\n stringSplitConfig,\n stringToHashBucketFastConfig,\n subConfig,\n sumConfig,\n tanConfig,\n tanhConfig,\n tensorScatterUpdateConfig,\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nconst 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(\n webGLVersion: number,\n customCanvas?: HTMLCanvasElement|OffscreenCanvas): WebGLRenderingContext {\n if (!(webGLVersion in contexts) || customCanvas != null) {\n const newCtx = getWebGLRenderingContext(webGLVersion, customCanvas);\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 == null || 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 // Use canvas element for Safari, since its offscreen canvas does not support\n // fencing.\n if (!env().getBool('IS_SAFARI') && typeof OffscreenCanvas !== 'undefined' &&\n 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(\n webGLVersion: number,\n customCanvas?: HTMLCanvasElement|OffscreenCanvas): WebGLRenderingContext {\n if (webGLVersion !== 1 && webGLVersion !== 2) {\n throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');\n }\n const canvas =\n customCanvas == null ? createCanvas(webGLVersion) : customCanvas;\n\n canvas.addEventListener('webglcontextlost', (ev: Event) => {\n ev.preventDefault();\n delete contexts[webGLVersion];\n }, false);\n\n if (env().getBool('SOFTWARE_WEBGL_ENABLED')) {\n WEBGL_ATTRIBUTES.failIfMajorPerformanceCaveat = false;\n }\n\n if (webGLVersion === 1) {\n return (\n // tslint:disable-next-line\n canvas.getContext('webgl', WEBGL_ATTRIBUTES) as WebGLRenderingContext ||\n (canvas as HTMLCanvasElement)\n .getContext('experimental-webgl',\n WEBGL_ATTRIBUTES) as 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 Texture {\n texture: WebGLTexture;\n texShape: [number, number];\n}\nexport interface TextureData {\n // Required.\n shape: number[];\n dtype: DataType;\n\n // Optional.\n values?: backend_util.BackendValues;\n texture?: Texture;\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 downloadTextureFormat = glany.RGBA8;\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 downloadTextureFormat = gl.RGBA;\n }\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(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(\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(\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 (env().get('ENGINE_COMPILE_ONLY')) {\n return fragmentShader;\n }\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;\nexport function 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(\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 (env().get('ENGINE_COMPILE_ONLY')) {\n return;\n }\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\n/// validateProgram is effectively \"If we `useProgram(program); drawArrays();`,\n/// give feedback in log about perf/correctness warnings or errors that would\n/// occur.\"\n/// So make sure we set up all vertex/texture/sampler/uniform data before\n/// calling validateProgram!\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(\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(\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(\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(\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(\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(\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 let maxSizeForNarrowTex =\n env().getNumber('WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE');\n if (maxSizeForNarrowTex === Infinity &&\n env().getBool('WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE')) {\n maxSizeForNarrowTex = maxTexSize / 2;\n }\n\n if (isPacked) {\n maxTexSize = maxTexSize * 2;\n maxSizeForNarrowTex = maxSizeForNarrowTex * 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 let textureShape: [number, number] = null;\n if (logShape.length <= 1 && size <= maxTexSize) {\n textureShape = [1, size];\n } else if (\n logShape.length === 2 && logShape[0] <= maxTexSize &&\n logShape[1] <= maxTexSize) {\n textureShape = logShape as [number, number];\n } else if (\n logShape.length === 3 && logShape[0] * logShape[1] <= maxTexSize &&\n logShape[2] <= maxTexSize) {\n textureShape = [logShape[0] * logShape[1], logShape[2]];\n } else if (\n logShape.length === 3 && logShape[0] <= maxTexSize &&\n logShape[1] * logShape[2] <= maxTexSize) {\n textureShape = [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 textureShape = [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 textureShape = [logShape[0], logShape[1] * logShape[2] * logShape[3]];\n }\n\n // true if one edge length is 1 (1 or 2, if packed), while another edge\n // length exceeds maxSizeForNarrowTex.\n const isLongNarrowTex = textureShape != null &&\n Math.max(...textureShape) > maxSizeForNarrowTex &&\n Math.min(...textureShape) <= (isPacked ? 2 : 1) &&\n Math.min(...textureShape) > 0;\n\n if (textureShape == null || isLongNarrowTex) {\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 textureShape =\n util.sizeToSquarishShape(size).map(d => d * 2) as [number, number];\n } else {\n textureShape = util.sizeToSquarishShape(size);\n }\n }\n\n return textureShape;\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[shape1.length - 1];\n const shape2Cols = shape2[shape2.length - 1];\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/** Whether we will pack conv2dTranspose op. */\nENV.registerFlag('WEBGL_PACK_CONV2DTRANSPOSE', () => 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 (!(typeof threshold === 'number')) {\n throw new Error('WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but ' +\n `got ${threshold}.`);\n }\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() ? 1 : -1;\n },\n threshold => {\n if (!(typeof threshold === 'number')) {\n throw new Error('WEBGL_FLUSH_THRESHOLD must be a number but got ' +\n `${threshold}.`);\n }\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/** Whether we will use the experimental conv op. */\nENV.registerFlag('WEBGL_EXP_CONV', () => false);\n\n/**\n * If the device performance is low or if no hardware GPU is available, whether\n * software WebGL will be used.\n */\nENV.registerFlag('SOFTWARE_WEBGL_ENABLED', () => ENV.getBool('IS_TEST'));\n\n/**\n * For narrow texture (physical height or physical width is 1), if the length of\n * any texture edges exceed the threshold, the texture will be reshaped to be\n * more squarish.\n *\n * This flag is used to help some GPUs that could not provide correct\n * interpolations for long skinny triangles. We found Mali GPU probably has this\n * problem: https://github.com/tensorflow/tfjs/issues/6775.\n */\nENV.registerFlag('WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE', () => Infinity);\n\n/**\n * If the flag is set to true, the max size of the narrow texture will be auto\n * computed and it will be considerred as a threshold to reshape the narrow\n * texture to be more squarish.\n *\n * This flag is used to help some GPUs that could not provide correct\n * interpolations for long skinny triangles. We found Mali GPU probably has this\n * problem: https://github.com/tensorflow/tfjs/issues/6775.\n */\nENV.registerFlag('WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE', () => false);\n\n/**\n * Whether to use the customized isnan. It's only useful for webgl2 since webgl1\n * doesn't have the builtin isnan.\n */\nENV.registerFlag('WEBGL2_ISNAN_CUSTOM', () => false);\n\n/** Experimental flag, whether enter compile only phase. */\nENV.registerFlag('ENGINE_COMPILE_ONLY', () => false);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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. Since WebGL2 supports uint type and\n // floatBitsToUinT built-in function, we could implment isnan following\n // IEEE 754 rules.\n // NaN defination in IEEE 754-1985 is :\n // - sign = either 0 or 1.\n // - biased exponent = all 1 bits.\n // - fraction = anything except all 0 bits (since all 0 bits represents\n // infinity).\n // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers\n defineSpecialNaN = env().getBool('WEBGL2_ISNAN_CUSTOM') ? `\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\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 '';\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 getOutputLogicalCoordinatesFromFlatIndexByUniform(\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\n// Produces GLSL code that computes strides.\nfunction symbolicallyComputeStrides(\n indicesArr: number[], variableName: string): string[] {\n const numCoords = indicesArr.length;\n const shape = indicesArr.map(d => `${variableName}[${d}]`);\n const strides = new Array(numCoords - 1);\n strides[numCoords - 2] = shape[numCoords - 1];\n for (let i = numCoords - 3; i >= 0; --i) {\n strides[i] = `(${strides[i + 1]} * ${shape[i + 1]})`;\n }\n\n return strides;\n}\n\nexport function getLogicalCoordinatesFromFlatIndexByUniform(\n coords: string[], variableName: string, index = 'index'): string {\n const indicesArray = coords.map((_, i) => i);\n const strides = symbolicallyComputeStrides(indicesArray, variableName);\n return strides\n .map((_, i) => {\n const line1 = `int ${coords[i]} = ${index} / ${strides[i]}`;\n const line2 = i === strides.length - 1 ?\n `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${strides[i]}` :\n `index -= ${coords[i]} * ${strides[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 function getFlatIndexFrom3DOutput(): string {\n return `\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[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 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.getOutputLogicalCoordinatesFromFlatIndexByUniform(\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.getOutputLogicalCoordinatesFromFlatIndexByUniform(\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, keptDims} = 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, keptDims};\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, GPGPUContextProgram} from './gpgpu_context';\nimport * as shader_compiler from './shader_compiler';\nimport {InputInfo, ShapeInfo, UniformType} from './shader_compiler';\nimport {PackingScheme, TextureData, TextureUsage} from './tex_util';\nimport {createFragmentShader} from './webgl_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 extends GPGPUBinaryLocations {\n webGLProgram: GPGPUContextProgram;\n program: GPGPUProgram;\n source: string;\n fragmentShader: WebGLShader;\n inShapeInfos: ShapeInfo[];\n outShapeInfo: ShapeInfo;\n}\n\nexport interface GPGPUBinaryLocations {\n customUniformLocations?: WebGLUniformLocation[];\n infLoc: WebGLUniformLocation;\n nanLoc: WebGLUniformLocation;\n outShapeLocation?: WebGLUniformLocation;\n outShapeStridesLocation?: WebGLUniformLocation;\n outTexShapeLocation?: WebGLUniformLocation;\n variablesLocations?: GPGPUVariableLocations[];\n}\n\nexport interface GPGPUVariableLocations {\n name: string;\n uniform: WebGLUniformLocation;\n offset: WebGLUniformLocation;\n shape?: WebGLUniformLocation;\n texShape?: 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(\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 const fragmentShader = createFragmentShader(gpgpu.gl, source);\n const webGLProgram = gpgpu.createProgram(fragmentShader);\n\n if (!env().get('ENGINE_COMPILE_ONLY')) {\n gpgpu.buildVao(webGLProgram);\n return {\n program,\n fragmentShader,\n source,\n webGLProgram,\n inShapeInfos,\n outShapeInfo,\n ...getUniformLocations(gpgpu, program, webGLProgram)\n };\n } else {\n return {\n program,\n fragmentShader,\n source,\n webGLProgram,\n inShapeInfos,\n outShapeInfo,\n variablesLocations: null,\n customUniformLocations: null,\n infLoc: null,\n nanLoc: null,\n outShapeLocation: null,\n outShapeStridesLocation: null,\n outTexShapeLocation: null\n };\n }\n}\n\nexport function getUniformLocations(\n gpgpu: GPGPUContext, program: GPGPUProgram,\n webGLProgram: WebGLProgram): GPGPUBinaryLocations {\n const variablesLocations: GPGPUVariableLocations[] = [];\n const customUniformLocations: WebGLUniformLocation[] = [];\n let outShapeLocation: WebGLUniformLocation;\n let outTexShapeLocation: WebGLUniformLocation;\n let outShapeStridesLocation: WebGLUniformLocation;\n let infLoc: WebGLUniformLocation = null;\n let nanLoc: WebGLUniformLocation = null;\n\n // Add special uniforms (NAN, INFINITY)\n 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 for (const varName of program.variableNames) {\n const varLocs: GPGPUVariableLocations = {\n name: varName,\n uniform: gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow),\n offset: gpgpu.getUniformLocation(\n webGLProgram, `offset${varName}`, shouldThrow),\n };\n if (program.enableShapeUniforms) {\n varLocs.shape = gpgpu.getUniformLocation(\n webGLProgram, `${varName}Shape`, shouldThrow);\n varLocs.texShape = gpgpu.getUniformLocation(\n webGLProgram, `${varName}TexShape`, shouldThrow);\n }\n\n variablesLocations.push(varLocs);\n }\n\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 if (program.customUniforms) {\n for (const d of program.customUniforms) {\n customUniformLocations.push(\n gpgpu.getUniformLocation(webGLProgram, d.name, shouldThrow));\n }\n }\n\n return {\n variablesLocations,\n customUniformLocations,\n infLoc,\n nanLoc,\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(\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(\n outTex.texture, outTexShape[0], outTexShape[1]);\n } else {\n gpgpu.setOutputMatrixTexture(\n outTex.texture, outTexShape[0], outTexShape[1]);\n }\n gpgpu.setProgram(binary.webGLProgram);\n gpgpu.bindVertexArray(binary.webGLProgram.vao);\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 for (let i = 0; i < inputs.length; ++i) {\n const input = inputs[i];\n const {\n uniform: varLoc,\n offset: varOffsetLoc,\n shape: varShapeLoc,\n texShape: varTexShapeLoc,\n } = binary.variablesLocations[i];\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\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 continue;\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 continue;\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.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 for (let i = 0; i < binary.program.customUniforms.length; ++i) {\n const d = binary.program.customUniforms[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, keptDims} =\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 uniformShape.length === 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 =\n program.packedInputs || uniformShape.length > 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}_${\n useSqueezeShape ? keptDims : ''}_${uniformShape.length}_${isScalar}_${\n broadcastDims}_${isLogicalShapTexShapeEqual}_${rank1}_${rank2}_${\n rank34}_${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 * @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, useShapeUniforms} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\nimport {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 enableShapeUniforms: boolean;\n customUniforms = [{name: 'texShape', type: 'ivec2' as const }];\n\n constructor(outputShape: [number, number, number]) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n\n this.userCode = `\n ivec3 outCoordsFromFlatIndex(int index) {\n ${\n this.enableShapeUniforms ?\n shader_util.getOutputLogicalCoordinatesFromFlatIndexByUniform(\n ['r', 'c', 'd'], outputShape) :\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 * 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, useShapeUniforms} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\nimport {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 enableShapeUniforms: boolean;\n customUniforms = [{name: 'texShape', type: 'ivec2' as const }];\n\n constructor(outputShape: [number, number, number]) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n\n this.userCode = `\n ivec3 outCoordsFromFlatIndex(int index) {\n ${\n this.enableShapeUniforms ?\n shader_util.getOutputLogicalCoordinatesFromFlatIndexByUniform(\n ['r', 'c', 'd'], outputShape) :\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 * 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, useShapeUniforms} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\nconst CHANNEL_CHAR_TO_INDEX_MAP: Record = {\n 'R': 0,\n 'G': 1,\n 'B': 2,\n 'A': 3\n};\n\nexport class EncodeMatrixProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n enableShapeUniforms: boolean;\n customUniforms = [{name: 'texShape', type: 'ivec2' as const }];\n\n constructor(\n outputShape: [number, number, number], inputIsUnsignedByte = false,\n usedChannels = 'RGBA') {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n\n let output = `result`;\n if (inputIsUnsignedByte) {\n output = `floor(result * 255. + 0.5)`;\n }\n\n let mainLoop = '';\n for (let usedChannelIndex = 0; usedChannelIndex < usedChannels.length;\n usedChannelIndex++) {\n const curChannel = usedChannels[usedChannelIndex];\n mainLoop += `\n if(offset == ${usedChannelIndex}) {\n result = values[${CHANNEL_CHAR_TO_INDEX_MAP[curChannel]}];\n }`;\n }\n\n this.userCode = `\n ${\n this.enableShapeUniforms ? shader_util.getFlatIndexFrom3DOutput() :\n shader_util.getFlatIndexFrom3D(outputShape)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n int flatIndex = getFlatIndex(coords);\n float result = 0.;\n int offset = imod(flatIndex, ${usedChannels.length});\n\n flatIndex = idiv(flatIndex, ${usedChannels.length}, 1.);\n\n int r = flatIndex / texShape[1];\n if (r < texShape[0]) {\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${glsl.texture2D}(A, uv);\n ${mainLoop}\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, useShapeUniforms} 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 enableShapeUniforms: boolean;\n customUniforms = [{name: 'texShape', type: 'ivec2' as const }];\n\n constructor(\n outputShape: [number, number, number], inputIsUnsignedByte = false) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\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} < ${\n this.enableShapeUniforms ? 'outShape[2]' : `${outputShape[2]}`}) {\n localCoords[2] += ${col};\n if (localCoords[1] + ${row} < ${\n this.enableShapeUniforms ? 'outShape[1]' : `${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 int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[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 ${\n this.enableShapeUniforms ? shader_util.getFlatIndexFrom3DOutput() :\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 {env, PixelData, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {getGlslDifferences} from './glsl_version';\nimport * as tex_util from './tex_util';\nimport {Texture, 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): Texture {\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 if (env().getNumber('WEBGL_VERSION') === 1) {\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n tex2d, 0, internalFormat, width, height, 0, textureFormat,\n textureType, null));\n } else {\n webgl_util.callAndCheck(\n gl,\n () => (gl as WebGL2RenderingContext)\n .texStorage2D(tex2d, 1, internalFormat, width, height));\n }\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n\n return {texture, texShape: [height, width]};\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): Texture {\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): Texture {\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): Texture {\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): Texture {\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): Texture {\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 if (env().getNumber('WEBGL_VERSION') === 2) {\n webgl_util.callAndCheck(\n gl,\n () => gl.texSubImage2D(\n gl.TEXTURE_2D, 0, 0, 0, width, height, gl.RGBA, texelDataType,\n dataForUpload));\n } else {\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\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 if (env().getNumber('WEBGL_VERSION') === 2) {\n webgl_util.callAndCheck(\n gl,\n () => gl.texSubImage2D(\n gl.TEXTURE_2D, 0, 0, 0, pixels.width, pixels.height, 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, pixels.width, pixels.height, 0,\n gl.RGBA, gl.UNSIGNED_BYTE, (pixels as PixelData).data));\n }\n } else {\n if (env().getNumber('WEBGL_VERSION') === 2) {\n webgl_util.callAndCheck(\n gl,\n () => gl.texSubImage2D(\n gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE,\n (pixels as ImageData | HTMLImageElement | HTMLCanvasElement |\n HTMLVideoElement | ImageBitmap)));\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\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 {Texture, TextureConfig} from './tex_util';\nimport {WebGL1DisjointQueryTimerExtension, WebGL2DisjointQueryTimerExtension, WebGLParallelCompilationExtension} from './webgl_types';\nimport * as webgl_util from './webgl_util';\n\nexport interface FenceContext {\n query: WebGLQuery|WebGLSync;\n isFencePassed(): boolean;\n}\n\ntype WebGLVao = WebGLVertexArrayObject|WebGLVertexArrayObjectOES;\n\nexport interface GPGPUContextProgram extends WebGLProgram {\n vao: WebGLVao;\n}\n\nexport class GPGPUContext {\n gl: WebGLRenderingContext;\n textureFloatExtension: {};\n textureHalfFloatExtension: {};\n colorBufferFloatExtension: {};\n colorBufferHalfFloatExtension: {};\n disjointQueryTimerExtension: WebGL2DisjointQueryTimerExtension|\n WebGL1DisjointQueryTimerExtension;\n parallelCompilationExtension: WebGLParallelCompilationExtension;\n vertexBuffer: WebGLBuffer;\n indexBuffer: WebGLBuffer;\n framebuffer: WebGLFramebuffer;\n outputTexture: WebGLTexture|null = null;\n program: GPGPUContextProgram|null = null;\n private disposed = false;\n private disjoint: boolean;\n private vertexShader: WebGLShader;\n textureConfig: TextureConfig;\n\n createVertexArray: () => WebGLVao | null;\n bindVertexArray: (vao: WebGLVao|null) => void;\n deleteVertexArray: (vao: WebGLVao|null) => void;\n getVertexArray: () => WebGLVao | null;\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 gl = this.gl;\n\n if (env().getNumber('WEBGL_VERSION') === 2) {\n const gl2 = gl as WebGL2RenderingContext;\n this.createVertexArray = () => {\n return webgl_util.callAndCheck(gl2, () => gl2.createVertexArray());\n };\n this.bindVertexArray = (vao: WebGLVao|null) => {\n return webgl_util.callAndCheck(\n gl2, () => gl2.bindVertexArray(vao as WebGLVertexArrayObject));\n };\n this.deleteVertexArray = (vao: WebGLVao|null) => {\n return webgl_util.callAndCheck(\n gl2, () => gl2.deleteVertexArray(vao as WebGLVertexArrayObject));\n };\n this.getVertexArray = () => {\n return webgl_util.callAndCheck(\n gl2, () => gl2.getParameter(gl2.VERTEX_ARRAY_BINDING));\n };\n } else if (gl != null) {\n const ext = gl.getExtension('OES_vertex_array_object');\n if (ext == null) {\n throw new Error(\n 'All WebGL1 implementations are expected to offer' +\n ' OES_vertex_array_object.');\n }\n this.createVertexArray = () => {\n return webgl_util.callAndCheck(gl, () => ext.createVertexArrayOES());\n };\n this.bindVertexArray = (vao: WebGLVao|null) => {\n return webgl_util.callAndCheck(\n gl, () => ext.bindVertexArrayOES(vao as WebGLVertexArrayObjectOES));\n };\n this.deleteVertexArray = (vao: WebGLVao|null) => {\n return webgl_util.callAndCheck(\n gl,\n () => ext.deleteVertexArrayOES(vao as WebGLVertexArrayObjectOES));\n };\n this.getVertexArray = () => {\n return webgl_util.callAndCheck(\n gl, () => gl.getParameter(ext.VERTEX_ARRAY_BINDING_OES));\n };\n }\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 this.parallelCompilationExtension =\n this.gl.getExtension('KHR_parallel_shader_compile');\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): Texture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat32MatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createFloat16MatrixTexture(rows: number, columns: number): Texture {\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 Texture {\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 Texture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat16PackedMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createPackedMatrixTexture(rows: number, columns: number): Texture {\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 {\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 public createProgram(fragmentShader: WebGLShader): GPGPUContextProgram {\n this.throwIfDisposed();\n const gl = this.gl;\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\n const program2 = Object.assign(program, {vao: this.createVertexArray()});\n if (this.debug) {\n webgl_util.validateProgram(gl, program2);\n }\n return program2;\n }\n\n public buildVao(program: GPGPUContextProgram) {\n this.setProgram(program);\n this.bindVertexArray(program.vao);\n const gl = this.gl;\n // Bind index buffer, and vertex buffers based on program attrib\n // locations.\n webgl_util.callAndCheck(\n gl, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer));\n gpgpu_util.bindVertexProgramAttributeStreams(\n gl, program, this.vertexBuffer);\n }\n\n public deleteProgram(program: GPGPUContextProgram) {\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 this.deleteVertexArray(program.vao);\n }\n }\n\n public setProgram(program: GPGPUContextProgram|null) {\n this.throwIfDisposed();\n this.program = program;\n\n if (this.program != null) {\n if (this.debug) {\n webgl_util.validateProgram(this.gl, this.program);\n }\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 const boundVao = this.getVertexArray();\n console.assert(\n boundVao === this.program.vao,\n 'VAO changed between setProgram and executeProgram!');\n\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 {\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(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 let scheduleFn = undefined;\n if ('setTimeoutCustom' in env().platform) {\n scheduleFn = env().platform.setTimeoutCustom.bind(env().platform);\n }\n util.repeatedTry(() => {\n this.pollItems();\n // End the loop if no more items to poll.\n return this.itemsToPoll.length === 0;\n }, () => 0, null, scheduleFn);\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/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 bitwiseAndImpl: bitwiseAndImplCPU,\n castImpl: castImplCPU,\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 raggedGatherImpl: raggedGatherImplCPU,\n raggedRangeImpl: raggedRangeImplCPU,\n raggedTensorToTensorImpl: raggedTensorToTensorImplCPU,\n rangeImpl: rangeImplCPU,\n rsqrtImpl: rsqrtImplCPU,\n scatterImpl: scatterImplCPU,\n sigmoidImpl: sigmoidImplCPU,\n simpleAbsImpl: simpleAbsImplCPU,\n sliceImpl: sliceImplCPU,\n sparseFillEmptyRowsImpl: sparseFillEmptyRowsImplCPU,\n sparseReshapeImpl: sparseReshapeImplCPU,\n sparseSegmentReductionImpl: sparseSegmentReductionImplCPU,\n sqrtImpl: sqrtImplCPU,\n staticRegexReplaceImpl: staticRegexReplaceImplCPU,\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 bitwiseAndImplCPU,\n castImplCPU,\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 raggedGatherImplCPU,\n raggedRangeImplCPU,\n raggedTensorToTensorImplCPU,\n scatterImplCPU,\n sigmoidImplCPU,\n simpleAbsImplCPU,\n sliceImplCPU,\n sparseFillEmptyRowsImplCPU,\n sparseReshapeImplCPU,\n sparseSegmentReductionImplCPU,\n sqrtImplCPU,\n staticRegexReplaceImplCPU,\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, useShapeUniforms} 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 enableShapeUniforms: boolean;\n rank: number;\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 this.rank = outputShape.length;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n\n if (this.rank === 0) {\n this.userCode = `\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n `;\n } else {\n const channels = getChannels('rc', this.rank);\n const dtype = getCoordsDataType(this.rank);\n const outOfBoundsCondition = this.getOutOfBoundsCondition(channels);\n const setup = this.getSetup(channels);\n const output = this.getOutput(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 private getSourceCoordsArr(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 < this.rank; d++) {\n coord = `${dims[dims.length - 1 - d]},` + coord;\n }\n\n coords.push(coord);\n }\n }\n return coords;\n }\n\n private getOutOfBoundsCondition(dims: string[]): string {\n if (this.rank === 1) {\n return `rc > ${\n this.enableShapeUniforms ? 'outShape' : this.outputShape[0]}`;\n }\n\n let cond = '';\n for (let i = this.rank - 2; i < this.rank; i++) {\n cond += `${dims[i]} >= ${\n this.enableShapeUniforms ? `outShape[${i}]` : this.outputShape[i]}`;\n if (i < this.rank - 1) {\n cond += '||';\n }\n }\n\n return cond;\n }\n\n private getSetup(dims: string[]): string {\n if (this.rank === 1) {\n return '';\n }\n\n const innerDims = dims.slice(-2);\n const col = this.enableShapeUniforms ? `outShape[${this.rank} - 1]` :\n this.outputShape[this.rank - 1];\n const row = this.enableShapeUniforms ? `outShape[${this.rank} - 2]` :\n this.outputShape[this.rank - 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 >= ${col};\n bool rEdge = rp1 >= ${row};\n `;\n }\n\n private getOutput(dims: string[]): string {\n const sourceCoords = this.getSourceCoordsArr(dims);\n if (this.rank === 1) {\n const outShape =\n this.enableShapeUniforms ? 'outShape' : this.outputShape[0];\n return `getA(rc), (rc + 1 >= ${outShape} ? 0. : getA(rc + 1)), 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","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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';\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 enableShapeUniforms: boolean;\n customUniforms = [{name: 'inputShape', type: 'ivec3' as const }];\n\n constructor(outputShape: [number, number, number], inputShape: [\n number, number, number\n ]) {\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\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, this.enableShapeUniforms)}\n ${\n this.enableShapeUniforms ? shader_util.getFlatIndexFrom3DOutput() :\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 = ${this.enableShapeUniforms ? 'outShape[1]' : outputShape[1]};\n int cols = ${this.enableShapeUniforms ? 'outShape[2]' : outputShape[2]};\n\n ${mainLoop}\n\n setOutput(result);\n }\n `;\n }\n}\n\nfunction getReshapedInputCoords(\n shape: [number, number, number], enableShapeUniforms: boolean): string {\n const coordsFromIndexSnippet = enableShapeUniforms ?\n shader_util.getLogicalCoordinatesFromFlatIndexByUniform(\n ['r', 'c', 'd'], 'inputShape') :\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, Texture, TextureConfig, TextureUsage} from './tex_util';\n\nexport class TextureManager {\n private numUsedTextures = 0;\n private numFreeTextures = 0;\n private _numBytesAllocated = 0;\n // Number of bytes that have been allocated and available for reuse.\n private _numBytesFree = 0;\n private freeTextures: Record = {};\n private usedTextures: Record = {};\n private logEnabled = false;\n\n constructor(private readonly gpgpu: GPGPUContext) {}\n\n acquireTexture(\n shapeRC: [number, number], usage: TextureUsage,\n isPacked: boolean): Texture {\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].pop();\n this.usedTextures[shapeKey].push(newTexture);\n return newTexture;\n }\n\n let newTexture: Texture;\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: Texture, shape: [number, number], logicalTexType: TextureUsage,\n 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()\n .getNumber('WEBGL_DELETE_TEXTURE_THRESHOLD');\n if (deleteTexThreshold !== -1 &&\n this._numBytesAllocated > deleteTexThreshold) {\n this.gpgpu.deleteMatrixTexture(texture.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 && texList.indexOf(texture);\n if (texIndex == null || texIndex < 0) {\n throw new Error(\n 'Cannot release a texture that was never provided by this ' +\n 'texture manager');\n }\n texList[texIndex] = texList[texList.length - 1];\n texList.pop();\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.texture);\n });\n }\n for (const texShape in this.usedTextures) {\n this.usedTextures[texShape].forEach(tex => {\n this.gpgpu.deleteMatrixTexture(tex.texture);\n });\n }\n // TODO: Assign non-null value (empty object) to textures after disposed.\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 } else if (internalFormat === glany.RGBA8) {\n return 4;\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, useShapeUniforms} 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 enableShapeUniforms: boolean;\n\n constructor(outputShape: number[]) {\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\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, DataToGPUWebGLOption, DataType, engine, env, GPUData, kernel_impls, KernelBackend, MemoryInfo, nextFrame, NumericDataType, Rank, RecursiveArray, scalar, ShapeMap, Tensor, Tensor2D, TensorBuffer, TensorInfo, tidy, TimingInfo, TypedArray, util, WebGLData} from '@tensorflow/tfjs-core';\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 {getUniformLocations, 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 {Texture, 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;\n};\n\nexport type TimerNode = RecursiveArray|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;\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 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();\n\n // Used to count the number of 'shallow' sliced tensors that point to the\n // same data id.\n dataRefCount = new WeakMap();\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(gpuResource?: GPGPUContext|HTMLCanvasElement|OffscreenCanvas) {\n super();\n if (!env().getBool('HAS_WEBGL')) {\n throw new Error('WebGL is not supported on this device');\n }\n\n let newGPGPU;\n if (gpuResource != null) {\n if (gpuResource instanceof GPGPUContext) {\n newGPGPU = gpuResource;\n } else {\n const gl =\n getWebGLContext(env().getNumber('WEBGL_VERSION'), gpuResource);\n newGPGPU = new GPGPUContext(gl);\n }\n this.binaryCache = {};\n this.gpgpuCreatedLocally = false;\n } else {\n const gl = getWebGLContext(env().getNumber('WEBGL_VERSION'));\n newGPGPU = new GPGPUContext(gl);\n this.binaryCache = getBinaryCache(env().getNumber('WEBGL_VERSION'));\n this.gpgpuCreatedLocally = true;\n }\n\n this.gpgpu = newGPGPU;\n this.canvas = this.gpgpu.gl.canvas;\n this.textureManager = new TextureManager(this.gpgpu);\n this.numMBBeforeWarning = numMBBeforeWarning();\n this.texData = new DataStorage(this, engine());\n }\n\n override numDataIds() {\n return this.texData.numDataIds() - this.pendingDeletes;\n }\n\n // Writes a new entry to the data store with a WebGL texture, and registers it\n // to the texture manager.\n writeTexture(\n texture: WebGLTexture, shape: number[], dtype: DataType,\n texHeight: number, texWidth: number, channels: string): DataId {\n // Temporarily create an tensor info to make the texture compatible with\n // the runWebGLProgram's input.\n const input = this.makeTensorInfo(shape, dtype);\n const inData = this.texData.get(input.dataId);\n // Even though the input texture could be unpacked or dense packed, it is\n // always considered as unpacked for EncodeMatrixProgram.\n inData.isPacked = false;\n\n // Bind texture to the input tensor.\n inData.texture = {texture, texShape: [texHeight, texWidth]};\n inData.texShape = [texHeight, texWidth];\n\n const shapeAs3D = webgl_util.getShapeAs3D(shape);\n const program =\n new EncodeMatrixProgram(shapeAs3D, false /* isByteArray */, channels);\n const output =\n this.runWebGLProgram(program, [input], dtype, [[texHeight, texWidth]]);\n output.shape = shape;\n\n // Unbind the texture from the input tensor to avoid the texture being\n // released.\n inData.texture = null;\n this.disposeIntermediateTensorInfo(input);\n\n return output.dataId;\n }\n\n override write(values: BackendValues, shape: number[], dtype: DataType):\n 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 override 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 override 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 override 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 override 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 override async read(dataId: DataId): Promise {\n if (this.pendingRead.has(dataId)) {\n const subscribers = this.pendingRead.get(dataId);\n return new Promise(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('DEBUG')) {\n // getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') caused a blocking GPU call.\n // For performance reason, only check it for debugging. In production,\n // it doesn't handle this use case anyway, so behavior is not changed.\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\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.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 /**\n * Read tensor to a new texture that is densely packed for ease of use.\n * @param dataId The source tensor.\n * @param options\n * customTexShape: Optional. If set, will use the user defined texture\n * shape to create the texture.\n */\n override readToGPU(dataId: DataId, options: DataToGPUWebGLOption = {}):\n GPUData {\n const texData = this.texData.get(dataId);\n const {values, shape, slice, dtype, isPacked, texture} = texData;\n\n if (dtype === 'complex64') {\n throw new Error('Does not support reading texture for complex64 dtype.');\n }\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 gpuResouorce = this.readToGPU(res, options);\n this.disposeIntermediateTensorInfo(res);\n return gpuResouorce;\n }\n\n if (texture == null) {\n if (values != null) {\n throw new Error('Data is not on GPU but on CPU.');\n } else {\n throw new Error('There is no data on GPU or CPU.');\n }\n }\n\n // Decode the texture so that it is stored densely (using four channels).\n const tmpTarget = this.decode(dataId, options.customTexShape);\n\n // Make engine track this tensor, so that we can dispose it later.\n const tensorRef = engine().makeTensorFromTensorInfo(tmpTarget);\n\n const tmpData = this.texData.get(tmpTarget.dataId);\n return {tensorRef, ...tmpData.texture};\n }\n\n bufferSync(t: TensorInfo):\n TensorBuffer {\n const data = this.readSync(t.dataId);\n if (t.dtype === 'string') {\n try {\n // Decode the bytes into string.\n const strings = (data as Uint8Array[]).map(d => util.decodeString(d));\n return buffer(t.shape as ShapeMap[R], t.dtype, strings) as\n TensorBuffer;\n } catch {\n throw new Error('Failed to decode encoded string bytes into utf-8');\n }\n }\n return buffer(t.shape as ShapeMap[R], t.dtype, data as TypedArray) as\n TensorBuffer;\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 =\n this.gpgpu\n .downloadMatrixFromPackedTexture(\n tmpData.texture.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 = this.gpgpu\n .downloadByteEncodedFloatMatrixFromOutputTexture(\n tmpData.texture.texture, tmpData.texShape[0],\n tmpData.texShape[1])\n .subarray(0, size);\n this.disposeIntermediateTensorInfo(output);\n\n return vals;\n }\n\n override timerAvailable(): boolean {\n return env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0;\n }\n\n override time(f: () => void): Promise {\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 return (async () => {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') >\n 0) {\n const kernelMs = await Promise.all(flattenedActiveTimerQueries);\n\n res['kernelMs'] = util.sum(kernelMs);\n res['getExtraProfileInfo'] = () =>\n kernelMs\n .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 }\n override 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 {\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 override 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.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().makeTensorFromTensorInfo(outInfo);\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(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().makeTensorFromTensorInfo(outInfo) 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 unknown 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(\n shape: number[], dtype: DataType, values?: BackendValues): T {\n return engine().makeTensorFromTensorInfo(\n this.makeTensorInfo(shape, dtype, values), 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 customValues = [input3DShape];\n const output = this.runWebGLProgram(\n program, [input3D], input.dtype, customValues,\n preventEagerUnpackingOfOutput);\n return {dataId: output.dataId, shape: afterShape, dtype: output.dtype};\n }\n\n private decode(dataId: DataId, customTexShape?: [number, number]):\n TensorInfo {\n const texData = this.texData.get(dataId);\n const {isPacked, shape, dtype} = texData;\n if (customTexShape != null) {\n const size = util.sizeFromShape(shape);\n const texSize = customTexShape[0] * customTexShape[1] * 4;\n util.assert(\n size <= texSize,\n () => 'customTexShape is too small. ' +\n 'Row * Column * 4 should be equal or larger than the ' +\n 'size of the tensor data.');\n }\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 customValues =\n [customTexShape != null ? customTexShape :\n tex_util.getDenseTexShape(shapeAs3D)];\n const out = this.runWebGLProgram(\n program, [{shape: shapeAs3D, dtype, dataId}], dtype, customValues,\n preventEagerUnpackingOfOutput, customTexShape);\n return {dtype, shape, dataId: out.dataId};\n }\n\n runWebGLProgram(\n program: GPGPUProgram, inputs: TensorInfo[], outputDtype: DataType,\n customUniformValues?: number[][], preventEagerUnpackingOfOutput = false,\n customTexShape?: [number, number]): 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 = customTexShape != null ?\n customTexShape :\n 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\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 }\n\n this.uploadToGPU(input.dataId);\n 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 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 if (!env().get('ENGINE_COMPILE_ONLY')) {\n gpgpu_math.runProgram(\n this.gpgpu, binary, inputsData, outputData, customUniformValues);\n }\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().getNumber('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 override 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 override 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 override 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 // This texShape may not be the final texture shape. For packed or dense\n // textures, the texShape will be changed when textures are created.\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 =\n values instanceof Uint8Array || values instanceof Uint8ClampedArray;\n\n // texture for float array is PhysicalTextureType.PACKED_2X2_FLOAT32, we\n // need to make sure the upload uses the same packed size\n if (isPacked || !isByteArray) {\n [width, height] = tex_util.getPackedMatrixTextureShapeWidthHeight(\n texShape[0], texShape[1]);\n }\n\n if (isPacked) {\n program = new EncodeMatrixPackedProgram(shapeAs3D, isByteArray);\n } else {\n program = new EncodeMatrixProgram(shapeAs3D, isByteArray);\n }\n\n // TexShape for float array needs to be the original shape, which byte\n // array needs to be packed size. This allow the data upload shape to be\n // matched with texture creation logic.\n const tempDenseInputTexShape: [number, number] =\n isByteArray ? [height, width] : texShape;\n const tempDenseInputHandle =\n this.makeTensorInfo(tempDenseInputTexShape, dtype);\n const tempDenseInputTexData =\n this.texData.get(tempDenseInputHandle.dataId);\n if (isByteArray) {\n tempDenseInputTexData.usage = TextureUsage.PIXELS;\n } else {\n tempDenseInputTexData.usage = TextureUsage.UPLOAD;\n }\n tempDenseInputTexData.texShape = tempDenseInputTexShape;\n this.gpgpu.uploadDenseMatrixToTexture(\n this.getTexture(tempDenseInputHandle.dataId), width, height,\n values as TypedArray);\n\n const customValues = [[height, width]];\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, customValues,\n preventEagerUnpacking);\n\n // Have the original texture assume the identity of the encoded output.\n const outputTexData = this.texData.get(encodedOutputTarget.dataId);\n texData.texShape = outputTexData.texShape;\n texData.isPacked = outputTexData.isPacked;\n texData.usage = outputTexData.usage;\n\n if (!env().get('ENGINE_COMPILE_ONLY')) {\n texData.texture = outputTexData.texture;\n // Once uploaded, don't store the values on cpu.\n texData.values = null;\n this.texData.delete(encodedOutputTarget.dataId);\n } else {\n this.disposeData(encodedOutputTarget.dataId);\n }\n\n this.disposeIntermediateTensorInfo(tempDenseInputHandle);\n\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 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): Texture {\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 checkCompileCompletion() {\n for (const [, binary] of Object.entries(this.binaryCache)) {\n this.checkCompletion_(binary);\n }\n }\n\n async checkCompileCompletionAsync(): Promise {\n const ps = [];\n if (this.gpgpu.parallelCompilationExtension) {\n for (const [, binary] of Object.entries(this.binaryCache)) {\n ps.push(this.checkCompletionAsync_(binary));\n }\n return Promise.all(ps);\n } else {\n for (const [, binary] of Object.entries(this.binaryCache)) {\n const p: Promise = new Promise((resolve) => {\n try {\n this.checkCompletion_(binary);\n resolve(true);\n } catch (error) {\n throw error;\n }\n });\n ps.push(p);\n }\n return Promise.all(ps);\n }\n }\n\n private async checkCompletionAsync_(binary: GPGPUBinary): Promise {\n if (this.gpgpu.gl.getProgramParameter(\n binary.webGLProgram,\n this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)) {\n return this.checkCompletion_(binary);\n } else {\n await nextFrame();\n return this.checkCompletionAsync_(binary);\n }\n }\n\n private checkCompletion_(binary: GPGPUBinary): boolean {\n if (this.gpgpu.gl.getProgramParameter(\n binary.webGLProgram, this.gpgpu.gl.LINK_STATUS) === false) {\n console.log(this.gpgpu.gl.getProgramInfoLog(binary.webGLProgram));\n if (this.gpgpu.gl.getShaderParameter(\n binary.fragmentShader, this.gpgpu.gl.COMPILE_STATUS) === false) {\n webgl_util.logShaderSourceAndInfoLog(\n binary.source,\n this.gpgpu.gl.getShaderInfoLog(binary.fragmentShader));\n throw new Error('Failed to compile fragment shader.');\n }\n throw new Error('Failed to link vertex and fragment shaders.');\n }\n return true;\n }\n\n getUniformLocations() {\n for (const binary of Object.values(this.binaryCache)) {\n // TODO: Iterating through all binaries to build VAOs is supposed to be in\n // a seperate function, like 'setVaos'. However, to avoid breaking changes\n // for the users using parallel compile feature now, buildVao is silently\n // added here.\n this.gpgpu.buildVao(binary.webGLProgram);\n\n const {\n variablesLocations,\n customUniformLocations,\n infLoc,\n nanLoc,\n outShapeLocation,\n outShapeStridesLocation,\n outTexShapeLocation\n } = getUniformLocations(this.gpgpu, binary.program, binary.webGLProgram);\n binary.variablesLocations = variablesLocations;\n binary.customUniformLocations = customUniformLocations;\n binary.infLoc = infLoc;\n binary.nanLoc = nanLoc;\n binary.outShapeLocation = outShapeLocation;\n binary.outShapeStridesLocation = outShapeStridesLocation;\n binary.outTexShapeLocation = outTexShapeLocation;\n }\n }\n\n /**\n * Create a TF.js tensor out of an existing WebGL texture. A new texture will\n * be created.\n */\n override createTensorFromGPUData(\n values: WebGLData, shape: number[], dtype: DataType): Tensor {\n values.channels = values.channels || 'RGBA';\n const {texture, height, width, channels} = values;\n const backend = engine().backend as MathBackendWebGL;\n\n // Have to throw an error, otherwise WebGL just warns and returns wrong\n // values.\n if (!backend.gpgpu.gl.isTexture(texture)) {\n throw new Error(\n `The texture is invalid. Also, please make sure the texture and ` +\n `the TFJS WebGL backend are using the same canvas. If you want to ` +\n `use your own custom canvas, you have to create and use the custom ` +\n `TFJS WebGL backend created from the canvas through ` +\n `'new tf.MathBackendWebGL(customCanvas)'.`);\n }\n\n const dataId =\n backend.writeTexture(texture, shape, dtype, height, width, channels);\n return engine().makeTensorFromDataId(dataId, shape, dtype, backend);\n }\n}\n\nfunction float32ToTypedArray(\n a: Float32Array, dtype: D): tf.DataTypeMap[D] {\n if (dtype === 'float32' || dtype === 'complex64') {\n return a as tf.DataTypeMap[D];\n } else if (dtype === 'int32' || dtype === 'bool') {\n const result = (dtype === 'int32') ? new Int32Array(a.length) :\n new Uint8Array(a.length);\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.round(a[i]);\n }\n return result as tf.DataTypeMap[D];\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.0';\nexport {version};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nimport * as gpgpu_util from './gpgpu_util';\nimport * as webgl_util from './webgl_util';\n\nexport {MathBackendWebGL, WebGLMemoryInfo, WebGLTimingInfo} from './backend_webgl';\nexport {setWebGLContext} from './canvas_util';\nexport {GPGPUContext} from './gpgpu_context';\nexport {GPGPUProgram} from './gpgpu_math';\n// WebGL specific utils.\nexport {gpgpu_util, webgl_util};\n\n/**\n * Enforce use of half precision textures if available on the platform.\n *\n * @doc {heading: 'Environment', namespace: 'webgl'}\n */\nexport function forceHalfFloat(): void {\n env().set('WEBGL_FORCE_F16_TEXTURES', true);\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// base.ts is the webgl backend without auto kernel registration.\n\nimport {device_util, registerBackend} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from './backend_webgl';\nexport {version as version_webgl} from './version';\n\nif (device_util.isBrowser()) {\n registerBackend('webgl', () => new MathBackendWebGL(), 2 /* priority */);\n}\n\n// Export webgl utilities\nexport * from './webgl';\n\n// Export forceHalfFlost under webgl namespace for the union bundle.\nimport {forceHalfFloat} from './webgl';\nexport const webgl = {forceHalfFloat};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\nexport const CHECK_NAN_SNIPPET = `\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n`;\n\nexport const SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';\nexport class BinaryOpProgram implements GPGPUProgram {\n variableNames = ['A', 'B'];\n outputShape: number[];\n userCode: string;\n enableShapeUniforms: boolean;\n\n constructor(op: string, aShape: number[], bShape: number[]) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n this.userCode = `\n float binaryOperation(float a, float b) {\n ${op}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport const CHECK_NAN_SNIPPET_PACKED = `\n result.r = isNaN.r ? NAN : result.r;\n result.g = isNaN.g ? NAN : result.g;\n result.b = isNaN.b ? NAN : result.b;\n result.a = isNaN.a ? NAN : result.a;\n`;\n\nexport const ELU_DER = `\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n`;\n\nexport const NOT_EQUAL = `\n return vec4(notEqual(a, b));\n`;\n\nexport class BinaryOpPackedProgram implements GPGPUProgram {\n variableNames = ['A', 'B'];\n outputShape: number[];\n userCode: string;\n supportsBroadcasting = true;\n packedInputs = true;\n packedOutput = true;\n enableShapeUniforms: boolean;\n\n constructor(\n op: string, aShape: number[], bShape: number[],\n checkOutOfBounds = false) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n const rank = this.outputShape.length;\n this.enableShapeUniforms = useShapeUniforms(rank);\n let checkOutOfBoundsString = '';\n if (checkOutOfBounds) {\n if (rank === 0 || util.sizeFromShape(this.outputShape) === 1) {\n checkOutOfBoundsString = `\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n `;\n } else {\n const dtype = getCoordsDataType(rank);\n checkOutOfBoundsString = `\n ${dtype} coords = getOutputCoords();\n `;\n if (rank === 1) {\n if (this.enableShapeUniforms) {\n checkOutOfBoundsString += `\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;\n } else {\n checkOutOfBoundsString += `\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;\n }\n } else {\n const channels = getChannels('coords', rank);\n if (this.enableShapeUniforms) {\n checkOutOfBoundsString += `\n bool nextRowOutOfBounds =\n (${channels[rank - 2]} + 1) >= outShape[${rank} - 2];\n bool nextColOutOfBounds =\n (${channels[rank - 1]} + 1) >= outShape[${rank} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `;\n } else {\n checkOutOfBoundsString += `\n bool nextRowOutOfBounds =\n (${channels[rank - 2]} + 1) >= ${this.outputShape[rank - 2]};\n bool nextColOutOfBounds =\n (${channels[rank - 1]} + 1) >= ${this.outputShape[rank - 1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `;\n }\n }\n }\n }\n\n this.userCode = `\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${op}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${checkOutOfBoundsString}\n\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Identity, IdentityInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function identity(\n args: {inputs: IdentityInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n backend.incRef(x.dataId);\n\n return {dataId: x.dataId, shape: x.shape, dtype: x.dtype};\n}\n\nexport const identityConfig: KernelConfig = {\n kernelName: Identity,\n backendName: 'webgl',\n kernelFunc: identity as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown 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], 'float32');\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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], 'float32');\n}\n\nexport const preluConfig: KernelConfig = {\n kernelName: Prelu,\n backendName: 'webgl',\n kernelFunc: prelu as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { backend_util, 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\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, useShapeUniforms} 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 enableShapeUniforms: boolean;\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 this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\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 = `imod(rc.x, ${aShape[0]})`;\n } else if (bShape[0] < aShape[0]) {\n batchBSnippet = `imod(rc.x, ${bShape[0]})`;\n }\n\n this.userCode = `\n ${activationSnippet}\n // Don't use uniform for sharedDimensionPacked for performance.\n const float sharedDimension = ${sharedDimensionPacked}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n int batchA = ${batchASnippet};\n int batchB = ${batchBSnippet};\n for (int i = 0; i < ${sharedDimensionPacked}; i++) {\n vec4 a = getMatrixA(batchA, ${aSample});\n vec4 b = getMatrixB(batchB, ${bSample});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${aSwizzle[0]} * ${bSwizzle[0]});\n result += (${aSwizzle[1]} * ${bSwizzle[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${addBiasSnippet}\n\n ${applyActivationSnippet}\n\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\n// (Ar + Ai)(Br + Bi) =\n// ArBr + ArBi + AiBr + AiBi = ArBr - AB + ArBi + AiBr\n// Yr = ArBr - AB\n// Yi = ArBi + AiBr\nexport const COMPLEX_MULTIPLY = {\n REAL: 'return areal * breal - aimag * bimag;',\n IMAG: 'return areal * bimag + aimag * breal;'\n};\n\nexport class BinaryOpComplexProgram implements GPGPUProgram {\n variableNames = ['AReal', 'AImag', 'BReal', 'BImag'];\n userCode: string;\n outputShape: number[];\n\n constructor(op: string, aShape: number[], bShape: number[]) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n\n this.userCode = `\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${op}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BinaryInputs, env, KernelConfig, Multiply, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport * as binaryop_complex_gpu from '../binaryop_complex_gpu';\nimport {BinaryOpComplexProgram} from '../binaryop_complex_gpu';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\nimport {multiplyImplCPU as cpuMultiply} from '../kernel_utils/shared';\n\nimport {complex} from './Complex';\n\nconst MUL = 'return a * b;';\n\nexport function multiply(\n args: {inputs: BinaryInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {a, b} = inputs;\n const dtype = backend_util.upcastType(a.dtype, b.dtype);\n\n if (a.dtype === 'complex64') {\n const aData = backend.texData.get(a.dataId);\n const bData = backend.texData.get(b.dataId);\n\n const realProgram = new BinaryOpComplexProgram(\n binaryop_complex_gpu.COMPLEX_MULTIPLY.REAL, a.shape, b.shape);\n const imagProgram = new BinaryOpComplexProgram(\n binaryop_complex_gpu.COMPLEX_MULTIPLY.IMAG, a.shape, b.shape);\n\n const inputs = [\n {\n dataId: aData.complexTensorInfos.real.dataId,\n dtype: aData.complexTensorInfos.real.dtype,\n shape: a.shape\n },\n {\n dataId: aData.complexTensorInfos.imag.dataId,\n dtype: aData.complexTensorInfos.imag.dtype,\n shape: a.shape\n },\n {\n dataId: bData.complexTensorInfos.real.dataId,\n dtype: bData.complexTensorInfos.real.dtype,\n shape: b.shape\n },\n {\n dataId: bData.complexTensorInfos.imag.dataId,\n dtype: bData.complexTensorInfos.imag.dtype,\n shape: b.shape\n }\n ];\n\n const realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');\n const imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');\n\n const complexOutput =\n complex({inputs: {real: realPart, imag: imagPart}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(imagPart);\n\n // TODO(annxingyuan): CPU forwarding for complex inputs.\n return complexOutput;\n }\n\n if (backend.shouldExecuteOnCPU([a, b])) {\n const aData = backend.texData.get(a.dataId);\n const bData = backend.texData.get(b.dataId);\n const [outValues, outShape] = cpuMultiply(\n a.shape, b.shape, aData.values as TypedArray,\n bData.values as TypedArray, dtype);\n\n const out = backend.makeTensorInfo(outShape, dtype);\n const outData = backend.texData.get(out.dataId);\n outData.values = outValues;\n return out;\n }\n\n let program: BinaryOpProgram|BinaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_BINARY_OPERATIONS')) {\n program = new BinaryOpPackedProgram(MUL, a.shape, b.shape);\n } else {\n program = new BinaryOpProgram(MUL, a.shape, b.shape);\n }\n\n return backend.runWebGLProgram(program, [a, b], dtype);\n}\n\nexport const multiplyConfig: KernelConfig = {\n kernelName: Multiply,\n backendName: 'webgl',\n kernelFunc: multiply\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 customValues = [input3DShape];\n const output = backend.runWebGLProgram(\n program, [input3D], input.dtype, customValues,\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 {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, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, sumOutType, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from './Reshape';\n\nimport {transposeImpl} from './Transpose_impl';\n\nexport function sumImpl(\n x: TensorInfo, axis: number|number[], keepDims: boolean,\n backend: MathBackendWebGL): TensorInfo {\n const reductionIndices = axis;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(reductionIndices, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const sumInputIsTransposed = permutedAxes != null;\n\n let sumInput = x;\n if (sumInputIsTransposed) {\n sumInput = transposeImpl(x, permutedAxes, backend);\n\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);\n const [sumOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(sumInput.shape, axes);\n\n let outShape = sumOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(sumOutShape, origAxes);\n }\n\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput = reshape(\n {inputs: {x: sumInput}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const outType = sumOutType(x.dtype);\n\n const reduced = reduce(reshapedInput, outType, 'sum', backend);\n const out =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n if (sumInputIsTransposed) {\n backend.disposeIntermediateTensorInfo(sumInput);\n }\n\n return out;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, broadcast_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 outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n a.shape.slice(0, -2), b.shape.slice(0, -2));\n const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${a.shape} and ` +\n `${b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const a3dShape: [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 unknown as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n\n out = backend.runWebGLProgram(program, inputs, dtype);\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: outShape}});\n intermediates.push(out);\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n return outReshaped;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {batchMatMulImpl} from './BatchMatMul_impl';\n\nexport function _fusedMatMul(args: {\n inputs: _FusedMatMulInputs,\n attrs: _FusedMatMulAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b, bias, preluActivationWeights} = inputs;\n const {transposeA, transposeB, activation, leakyreluAlpha} = attrs;\n\n return batchMatMulImpl({\n a,\n b,\n transposeA,\n transposeB,\n backend,\n bias,\n preluActivationWeights,\n leakyreluAlpha,\n activation\n });\n}\n\nexport const _fusedMatMulConfig: KernelConfig = {\n kernelName: _FusedMatMul,\n backendName: 'webgl',\n kernelFunc: _fusedMatMul as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Acos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ACOS = CHECK_NAN_SNIPPET + `\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n`;\n\nexport const acos = unaryKernelFunc({opSnippet: ACOS});\n\nexport const acosConfig: KernelConfig = {\n kernelName: Acos,\n backendName: 'webgl',\n kernelFunc: acos,\n};\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Acosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ACOSH = CHECK_NAN_SNIPPET + `\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));`;\n\nexport const acosh = unaryKernelFunc({opSnippet: ACOSH});\n\nexport const acoshConfig: KernelConfig = {\n kernelName: Acosh,\n backendName: 'webgl',\n kernelFunc: acosh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Add, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {addImplCPU as cpuAdd} from '../kernel_utils/shared';\n\nconst ADD = 'return a + b;';\n\nexport const addKernelFunc = binaryKernelFunc({\n opSnippet: ADD,\n packedOpSnippet: ADD,\n supportsComplex: true,\n cpuKernelImpl: cpuAdd\n});\n\nexport const addConfig: KernelConfig = {\n kernelName: Add,\n backendName: 'webgl',\n kernelFunc: addKernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AddNProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(outputShape: number[], shapes: number[][]) {\n this.outputShape = outputShape;\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const snippets: string[] = [];\n // Get target elements from every input tensor.\n this.variableNames.forEach(variable => {\n snippets.push(`float v${variable} = get${variable}AtOutCoords();`);\n });\n\n // Calculate the sum of all elements.\n const operation = this.variableNames\n .map(variable => {\n return `v${variable}`;\n })\n .join(' + ');\n\n this.userCode = `\n void main() {\n ${snippets.join('\\n ')}\n\n float result = ${operation};\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AddNPackedProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(outputShape: number[], shapes: number[][]) {\n this.outputShape = outputShape;\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const snippets: string[] = [];\n // Get target elements from every input tensor.\n this.variableNames.forEach(variable => {\n snippets.push(`vec4 v${variable} = get${variable}AtOutCoords();`);\n });\n\n // Calculate the sum of all elements.\n const operation = this.variableNames\n .map(variable => {\n return `v${variable}`;\n })\n .join(' + ');\n\n this.userCode = `\n void main() {\n ${snippets.join('\\n ')}\n\n vec4 result = ${operation};\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AddN, AddNInputs, env, KernelConfig, KernelFunc, TensorInfo, upcastType} from '@tensorflow/tfjs-core';\n\nimport {AddNProgram} from '../addn_gpu';\nimport {AddNPackedProgram} from '../addn_packed_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function addN(args: {inputs: AddNInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n\n const tensors = inputs;\n if (tensors.length === 1) {\n return identity({inputs: {x: tensors[0]}, backend});\n }\n\n // Limit the number of uploaded textures for optimization.\n if (tensors.length > env().getNumber('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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ArgMinMaxProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n reduceInfo: backend_util.ReduceInfo, op: 'max'|'min',\n firstPass: boolean) {\n const {windowSize, batchSize, outSize} = reduceInfo;\n if (!firstPass) {\n this.variableNames.push('bestIndicesA');\n }\n this.outputShape = [batchSize, outSize];\n const compOp = (op === 'max') ? '>' : '<';\n const indexSnippet = firstPass ?\n 'inOffset + i;' :\n 'round(getBestIndicesA(batch, inOffset + i));';\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${windowSize};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${windowSize}; i++) {\n int inIdx = ${indexSnippet};\n float candidate = getA(batch, inIdx);\n if (candidate ${compOp} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ArgMinMaxPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n shape: number[], windowSize: number, op: 'max'|'min',\n firstPass: boolean) {\n util.assert(\n shape.length > 2,\n () => `Packed arg${\n op.charAt(0).toUpperCase() +\n op.slice(1)} supports only inputs with rank above 2.`);\n const inSize = shape[shape.length - 1];\n const outSize = Math.ceil(inSize / windowSize);\n this.outputShape = shape.slice(0, -1);\n if (outSize > 1) {\n this.outputShape.push(outSize);\n }\n if (!firstPass) {\n this.variableNames.push('bestIndicesA');\n }\n const outShape = this.outputShape;\n const rank = outShape.length;\n const dtype = getCoordsDataType(rank);\n const coords = getChannels('coords', rank);\n\n let sourceLocSetup;\n let sourceRank;\n if (outSize === 1) {\n sourceRank = rank + 1;\n const sourceLocDType = getCoordsDataType(sourceRank);\n sourceLocSetup = `\n ${sourceLocDType} sourceLocR = ${sourceLocDType}(${coords.join()}, 0);\n ++${coords[rank - 1]};\n ${sourceLocDType} sourceLocG = ${sourceLocDType}(${coords.join()}, 0);\n ++${coords[rank - 2]};\n ${sourceLocDType} sourceLocA = ${sourceLocDType}(${coords.join()}, 0);\n --${coords[rank - 1]};\n ${sourceLocDType} sourceLocB = ${sourceLocDType}(${coords.join()}, 0);\n --${coords[rank - 2]};`;\n } else {\n sourceRank = rank;\n sourceLocSetup = `\n ${dtype} sourceLocR = coords;\n ++${coords[rank - 1]};\n ${dtype} sourceLocG = coords;\n ++${coords[rank - 2]};\n ${dtype} sourceLocA = coords;\n --${coords[rank - 1]};\n ${dtype} sourceLocB = coords;\n --${coords[rank - 2]};`;\n }\n const channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, sourceRank);\n const inChannel = '.' + channels[sourceRank - 1]; // e.g. \".b\" for rank 3.\n const intChannels = channels.map(x => 'int ' + x);\n const srcRCoords =\n getChannels('sourceLocR', sourceRank - 1).concat('inIdx.r');\n const srcGCoords =\n getChannels('sourceLocG', sourceRank - 1).concat('inIdx.g');\n const srcBCoords =\n getChannels('sourceLocB', sourceRank - 1).concat('inIdx.b');\n const srcACoords =\n getChannels('sourceLocA', sourceRank - 1).concat('inIdx.a');\n\n const compOp = (op === 'max') ? 'greaterThan' : 'lessThan';\n const fetchCandidateIdx = firstPass ? '' : `\n inIdx = round(vec4(getBestIndicesAChannel(${srcRCoords.join()}),\n getBestIndicesAChannel(${srcGCoords.join()}),\n getBestIndicesAChannel(${srcBCoords.join()}),\n getBestIndicesAChannel(${srcACoords.join()})));`;\n\n const fetchValue = `vec4(\n getAChannel(${srcRCoords.join()}),\n hasNextCol ? getAChannel(${srcGCoords.join()}) : 0.,\n hasNextRow ? getAChannel(${srcBCoords.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${srcACoords.join()}) : 0.)`;\n\n const getBestIndicesAChannelSnippet = firstPass ? '' : `\n float getBestIndicesAChannel(${intChannels.join()}) {\n return getChannel(getBestIndicesA(${channels.join()}),\n vec2(${channels.slice(-2).join()}));\n }`;\n\n this.userCode = `\n float getAChannel(${intChannels.join()}) {\n return getChannel(getA(${channels.join()}),\n vec2(${channels.slice(-2).join()}));\n }\n ${getBestIndicesAChannelSnippet}\n void main() {\n ${dtype} coords = getOutputCoords();\n bool hasNextCol = ${coords[rank - 1]} < ${outShape[rank - 1] - 1};\n bool hasNextRow = ${coords[rank - 2]} < ${outShape[rank - 2] - 1};\n ${sourceLocSetup}\n ivec4 srcIdx = ivec4(sourceLocR${inChannel}, sourceLocG${inChannel},\n sourceLocB${inChannel}, sourceLocA${inChannel}) * ${windowSize};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${fetchValue};\n\n for (int i = 0; i < ${windowSize}; i++) {\n inIdx = srcIdx;\n ${fetchCandidateIdx}\n vec4 candidate = ${fetchValue};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${compOp}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {ArgMinMaxProgram} from '../argminmax_gpu';\nimport {ArgMinMaxPackedProgram} from '../argminmax_packed_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reshape} from '../kernels/Reshape';\n\nfunction argReduce(\n backend: MathBackendWebGL, x: TensorInfo, reduceType: 'max'|'min',\n bestIndicesA: TensorInfo = null): TensorInfo {\n let batchSize = x.shape[0];\n let inSize = x.shape[1];\n if (bestIndicesA != null) {\n batchSize = bestIndicesA.shape[0];\n inSize = bestIndicesA.shape[1];\n }\n const windowSize = backend_util.computeOptimalWindowSize(inSize);\n const reduceInfo =\n {windowSize, inSize, batchSize, outSize: Math.ceil(inSize / windowSize)};\n const program =\n new ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);\n const inputs = [x];\n if (bestIndicesA != null) {\n inputs.push(bestIndicesA);\n }\n const output = backend.runWebGLProgram(program, inputs, 'int32');\n // No need to run another GPGPU program.\n if (output.shape[1] === 1) {\n return output;\n }\n const result = argReduce(backend, x, reduceType, output);\n backend.disposeIntermediateTensorInfo(output);\n return result;\n}\n\nfunction argReducePacked(\n backend: MathBackendWebGL, x: TensorInfo, reduceType: 'max'|'min',\n bestIndicesA: TensorInfo = null): TensorInfo {\n const inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;\n const inSize = inShape[inShape.length - 1];\n const windowSize = backend_util.computeOptimalWindowSize(inSize);\n const program = new ArgMinMaxPackedProgram(\n inShape, windowSize, reduceType, bestIndicesA == null);\n const inputs = bestIndicesA == null ? [x] : [x, bestIndicesA];\n const output = backend.runWebGLProgram(program, inputs, 'int32');\n if (output.shape.length === x.shape.length) {\n const result = argReducePacked(backend, x, reduceType, output);\n backend.disposeIntermediateTensorInfo(output);\n return result;\n }\n return output;\n}\n\nexport function argMinMaxReduce(\n backend: MathBackendWebGL, x: TensorInfo, axis: number,\n reduceType: 'min'|'max'): TensorInfo {\n const axes = [axis];\n backend_util.assertAxesAreInnerMostDims(\n 'arg' + reduceType.charAt(0).toUpperCase() + reduceType.slice(1), axes,\n x.shape.length);\n if (!env().getBool('WEBGL_PACK_REDUCE') || x.shape.length <= 2) {\n const intermediateTensorInfos = [];\n // 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 let xUnPacked = x;\n if (xIsPacked) {\n xUnPacked = backend.unpackTensor(x);\n intermediateTensorInfos.push(xUnPacked);\n }\n\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(xUnPacked.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D = reshape(\n {inputs: {x: xUnPacked}, backend, attrs: {shape: [-1, inSize]}});\n intermediateTensorInfos.push(a2D);\n\n const reduced = argReduce(backend, a2D, reduceType);\n intermediateTensorInfos.push(reduced);\n const reshaped =\n reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return reshaped;\n }\n return argReducePacked(backend, x, reduceType);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ArgMax, ArgMaxAttrs, ArgMaxInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {argMinMaxReduce} from '../kernel_utils/arg_min_max';\n\nimport {transpose} from './Transpose';\n\nexport function argMax(\n args:\n {inputs: ArgMaxInputs, backend: MathBackendWebGL, attrs: ArgMaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('argMax', [axes[0]], $x.shape.length);\n const out = argMinMaxReduce(backend, $x, axes[0], 'max');\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return out;\n}\n\nexport const argMaxConfig: KernelConfig = {\n kernelName: ArgMax,\n backendName: 'webgl',\n kernelFunc: argMax as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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';\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst ATAN2 = CHECK_NAN_SNIPPET + `\n return atan(a, b);\n`;\n\nconst ATAN2_PACKED = `\n vec4 result = atan(a, b);\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\n return result;\n`;\n\nexport const atan2 =\n binaryKernelFunc({opSnippet: ATAN2, packedOpSnippet: ATAN2_PACKED});\n\nexport const atan2Config: KernelConfig = {\n kernelName: Atan2,\n backendName: 'webgl',\n kernelFunc: atan2,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atanh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ATANH = CHECK_NAN_SNIPPET + `\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;`;\n\nexport const atanh = unaryKernelFunc({opSnippet: ATANH});\n\nexport const atanhConfig: KernelConfig = {\n kernelName: Atanh,\n backendName: 'webgl',\n kernelFunc: atanh,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Pool2DProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, poolType: 'max'|'avg',\n computePositions: boolean, flattenPositions = false,\n includeBatchInIndex = false) {\n if (poolType === 'avg' && computePositions) {\n throw new Error('Cannot compute positions for average pool.');\n }\n\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n this.outputShape = convInfo.outShape;\n\n const isAvgPool = poolType === 'avg';\n const batchFlattenPositionStr = `((batch * ${convInfo.inHeight} + xR) * ${\n convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;\n const flattenPositionStr =\n `(xR * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;\n\n let initializationValue = '0.0';\n if (!isAvgPool) {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n }\n\n if (computePositions) {\n const compareOp = '>=';\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${compareOp} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${\n flattenPositions ? (includeBatchInIndex ? batchFlattenPositionStr :\n flattenPositionStr) :\n `wR * ${effectiveFilterWidth} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `;\n return;\n }\n\n const compareOp = 'max';\n\n let returnValue = `${poolType}(${poolType}(${poolType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n if (poolType === 'avg') {\n returnValue = `avgValue / max(count, 1.0)`;\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 // Use `max(count, 1.0)` instead of `count` in case count === 0.0.\n // If count === 0.0, `avgValue` is always 0.0 and we change `count`'s\n // value to avoid dividing zero.\n returnValue = `avgValue / max(count, 1.0)`;\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 }\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 */\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AvgPool2DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const avgMultiplier = 1 / (filterHeight * filterWidth);\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float avgMultiplier = float(${avgMultiplier});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC+= ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class AvgPool3DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);\n\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n const float avgMultiplier = float(${avgMultiplier});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPool3DGrad, AvgPool3DGradAttrs, AvgPool3DGradInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {AvgPool3DBackpropProgram} from '../avg_pool_backprop_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function avgPool3DGrad(args: {\n inputs: AvgPool3DGradInputs,\n backend: MathBackendWebGL,\n attrs: AvgPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n const avgPoolBackpropProgram = new AvgPool3DBackpropProgram(convInfo);\n return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);\n}\n\nexport const avgPool3DGradConfig: KernelConfig = {\n kernelName: AvgPool3DGrad,\n backendName: 'webgl',\n kernelFunc: avgPool3DGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs, 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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class BatchNormProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n xShape: number[], meanShape: number[], varianceShape: number[],\n offsetShape: number[]|null, scaleShape: number[]|null,\n varianceEpsilon: number) {\n this.variableNames = ['x', 'mean', 'variance'];\n backend_util.assertAndGetBroadcastShape(xShape, meanShape);\n backend_util.assertAndGetBroadcastShape(xShape, varianceShape);\n\n let offsetSnippet = '0.0';\n if (offsetShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, offsetShape);\n this.variableNames.push('offset');\n offsetSnippet = 'getOffsetAtOutCoords()';\n }\n\n let scaleSnippet = '1.0';\n if (scaleShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, scaleShape);\n this.variableNames.push('scale');\n scaleSnippet = 'getScaleAtOutCoords()';\n }\n\n this.outputShape = xShape;\n this.userCode = `\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${offsetSnippet};\n float scale = ${scaleSnippet};\n float inv = scale * inversesqrt(variance + float(${varianceEpsilon}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class BatchNormPackedProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n xShape: number[], meanShape: number[], varianceShape: number[],\n offsetShape: number[]|null, scaleShape: number[]|null,\n varianceEpsilon: number) {\n this.variableNames = ['x', 'mean', 'variance'];\n backend_util.assertAndGetBroadcastShape(xShape, meanShape);\n backend_util.assertAndGetBroadcastShape(xShape, varianceShape);\n\n let offsetSnippet = 'vec4(0.0)';\n if (offsetShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, offsetShape);\n this.variableNames.push('offset');\n offsetSnippet = 'getOffsetAtOutCoords()';\n }\n\n let scaleSnippet = 'vec4(1.0)';\n if (scaleShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, scaleShape);\n this.variableNames.push('scale');\n scaleSnippet = 'getScaleAtOutCoords()';\n }\n\n this.outputShape = xShape;\n this.userCode = `\n void main() {\n vec4 offset = ${offsetSnippet};\n vec4 scale = ${scaleSnippet};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${varianceEpsilon}));\n\n setOutput((x - mean) * inv + offset);\n }\n `;\n }\n}\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BatchNormProgram} from '../batchnorm_gpu';\nimport {BatchNormPackedProgram} from '../batchnorm_packed_gpu';\n\nexport const batchNorm: (params: {\n inputs: FusedBatchNormInputs,\n backend: MathBackendWebGL,\n attrs: FusedBatchNormAttrs\n}) => TensorInfo = ({inputs, backend, attrs}) => {\n const {x, mean, variance, offset, scale} = inputs;\n\n util.assert(\n mean.shape.length === variance.shape.length,\n () => 'Batch normalization gradient requires mean and variance to have ' +\n 'equal ranks.');\n util.assert(\n offset == null || mean.shape.length === offset.shape.length,\n () => 'Batch normalization gradient requires mean and offset to have ' +\n 'equal ranks.');\n util.assert(\n scale == null || mean.shape.length === scale.shape.length,\n () => 'Batch normalization gradient requires mean and scale to have ' +\n 'equal ranks.');\n\n let {varianceEpsilon} = attrs;\n if (varianceEpsilon == null) {\n varianceEpsilon = 0.001;\n }\n\n const finalInputs = [x, mean, variance];\n\n let offsetShape = null;\n if (offset != null) {\n offsetShape = offset.shape;\n finalInputs.push(offset);\n }\n\n let scaleShape = null;\n if (scale != null) {\n scaleShape = scale.shape;\n finalInputs.push(scale);\n }\n\n const program = env().getBool('WEBGL_PACK_NORMALIZATION') ?\n new BatchNormPackedProgram(\n x.shape, mean.shape, variance.shape, offsetShape, scaleShape,\n varianceEpsilon) :\n new BatchNormProgram(\n x.shape, mean.shape, variance.shape, offsetShape, scaleShape,\n varianceEpsilon);\n const output =\n backend.runWebGLProgram(program, finalInputs, finalInputs[0].dtype);\n\n return output;\n};\n\nexport const batchNormConfig: KernelConfig = {\n kernelName: FusedBatchNorm,\n backendName: 'webgl',\n kernelFunc: batchNorm as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class SliceProgram implements GPGPUProgram {\n variableNames = ['source'];\n outputShape: number[];\n userCode: string;\n rank: number;\n customUniforms: Array<{name: string; arrayIndex: number; type: UniformType;}>;\n\n constructor(destSize: number[]) {\n this.outputShape = destSize;\n this.rank = destSize.length;\n\n const dtype = getCoordsDataType(this.rank);\n this.customUniforms = [{name: 'start', arrayIndex: this.rank, type: 'int'}];\n const sourceCoords = getCoords(this.rank);\n\n let body: string;\n const coordSum = destSize.map((_, i) => {\n return `sourceLoc.${coords[i]} = start[${i}] + coords.${coords[i]};`;\n });\n body = `\n ${dtype} sourceLoc;\n ${dtype} coords = getOutputCoords();\n ${coordSum.join('\\n')}\n `;\n this.userCode = `\n void main() {\n ${body}\n setOutput(getSource(${sourceCoords}));\n }\n `;\n }\n}\n\nconst coords = ['x', 'y', 'z', 'w', 'u', 'v'];\n\nfunction getCoords(rank: number): string {\n if (rank === 1) {\n return 'sourceLoc';\n } else if (rank <= 6) {\n return coords.slice(0, rank).map(x => 'sourceLoc.' + x).join(',');\n } else {\n throw Error(`Slicing for rank ${rank} is not yet supported`);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class SlicePackedProgram implements GPGPUProgram {\n variableNames = ['source'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n rank: number;\n customUniforms: Array<{name: string; arrayIndex: number; type: UniformType;}>;\n\n constructor(destSize: number[]) {\n this.outputShape = destSize;\n this.rank = destSize.length;\n this.customUniforms = [{name: 'start', arrayIndex: this.rank, type: 'int'}];\n const dtype = getCoordsDataType(this.rank);\n const coords = getChannels('coords', this.rank);\n const sourceLoc = getChannels('sourceLoc', this.rank);\n\n const innerDims =\n this.rank === 1 ? 'sourceLoc' : `vec2(${sourceLoc.slice(-2).join()})`;\n const getChannel =\n `getChannel(getSource(${sourceLoc.join()}), ${innerDims})`;\n const upperRow = `\n result.x = ${getChannel};\n if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {\n ++${sourceLoc[this.rank - 1]};\n result.y = ${getChannel};\n --${sourceLoc[this.rank - 1]};\n }\n `;\n const lowerRow = this.rank === 1 ? '' : `\n --${coords[this.rank - 1]};\n if (++${coords[this.rank - 2]} < ${destSize[this.rank - 2]}) {\n ++${sourceLoc[this.rank - 2]};\n result.z = ${getChannel};\n if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {\n ++${sourceLoc[this.rank - 1]};\n result.w = ${getChannel};\n }\n }\n `;\n\n const sourceLocSetup = this.rank <= 4 ?\n `sourceLoc = coords +\n ${dtype}(${destSize.map((_, i) => `start[${i}]`).join()});` :\n destSize.map((_, i) => `${sourceLoc[i]} = ${coords[i]} + start[${i}];`)\n .join('\\n');\n this.userCode = `\n void main() {\n ${dtype} coords = getOutputCoords();\n ${dtype} sourceLoc;\n ${sourceLocSetup}\n vec4 result = vec4(0.);\n ${upperRow}\n ${lowerRow}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Slice, slice_util, SliceAttrs, SliceInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sliceImplCPU} from '../kernel_utils/shared';\nimport {SliceProgram} from '../slice_gpu';\nimport {SlicePackedProgram} from '../slice_packed_gpu';\n\nfunction shallowSlice(\n x: TensorInfo, begin: number[], size: number[], backend: MathBackendWebGL) {\n const xTexData = backend.texData.get(x.dataId);\n const t = backend.makeTensorInfo(size, x.dtype);\n const newTexData = backend.texData.get(t.dataId);\n // Copy texture data from the original tensor.\n Object.assign(newTexData, xTexData);\n newTexData.refCount = 1;\n newTexData.shape = size;\n newTexData.dtype = x.dtype;\n let flatOffset =\n slice_util.computeFlatOffset(begin, util.computeStrides(x.shape));\n if (xTexData.slice) {\n // We are slicing an already sliced tensor, so we have to accumulate\n // the offset.\n flatOffset += xTexData.slice.flatOffset;\n }\n newTexData.slice = {\n flatOffset,\n // Point to the original dataId, which is used to do ref counting.\n origDataId: xTexData.slice && xTexData.slice.origDataId || x.dataId\n };\n\n // Increase the ref count for that data bucket.\n const refCount = backend.dataRefCount.get(newTexData.slice.origDataId) || 1;\n backend.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);\n return t;\n}\n\nexport function slice(\n args: {inputs: SliceInputs, backend: MathBackendWebGL, attrs: SliceAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {begin, size} = attrs;\n\n const [$begin, $size] = slice_util.parseSliceParams(x, begin, size);\n slice_util.assertParamsValid(x, $begin, $size);\n\n if (util.sizeFromShape($size) === 0) {\n return backend.makeTensorInfo($size, x.dtype, []);\n }\n\n // Run on cpu if dtype is string. For string, the backend represents it\n // as Uint8Array[], where each Uint8Array is a character. Given that the\n // computation is only on the outer array, uploading the whole data onto\n // gpu is wasteful. Also, currently webgl doesn't have a design to\n // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we\n // just run the kernel on cpu if dtype is string.\n if (backend.shouldExecuteOnCPU([x]) || x.dtype === 'string') {\n const xTexData = backend.texData.get(x.dataId);\n const outValues = sliceImplCPU(\n xTexData.values as TypedArray, $begin, $size, x.shape, x.dtype);\n return backend.makeTensorInfo($size, x.dtype, outValues);\n }\n\n const {isPacked} = backend.texData.get(x.dataId);\n const isContinous = slice_util.isSliceContinous(x.shape, $begin, $size);\n if (isPacked || !isContinous) {\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new SlicePackedProgram($size) :\n new SliceProgram($size);\n const customValues = [$begin];\n return backend.runWebGLProgram(program, [x], x.dtype, customValues);\n }\n backend.uploadToGPU(x.dataId);\n return shallowSlice(x, $begin, $size, backend);\n}\n\nexport const sliceConfig: KernelConfig = {\n kernelName: Slice,\n backendName: 'webgl',\n kernelFunc: slice as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BitwiseAnd, BitwiseAndInputs, env, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\nimport {bitwiseAndImplCPU as cpuBitwiseAnd} from '../kernel_utils/shared';\n\nexport const BITWISEAND = `\n int r = int(a.r) & int(b.r);\n int g = int(a.g) & int(b.g);\n int rb = int(a.b) & int(b.b);\n int ra = int(a.a) & int(b.a);\n return vec4(r, g, rb, ra);\n`;\n\nexport const BITWISEAND_UNPACKED = `\n return float(int(a.r) & int(b.r));\n`;\n\nexport function bitwiseAnd(args: {\n inputs: BitwiseAndInputs,\n backend: MathBackendWebGL,\n}): TensorInfo {\n const {inputs, backend} = args;\n const {a, b} = inputs;\n const shouldUsePackedProgram = env().getBool('WEBGL_PACK_BINARY_OPERATIONS');\n const versionNumber = env().getNumber('WEBGL_VERSION');\n\n // The type of a and b are ensured to be `int32` in core, therefore no need to\n // consider other type situations.\n if ((backend.shouldExecuteOnCPU([a, b])) || versionNumber === 1) {\n const aVals = backend.texData.get(a.dataId).values as TypedArray;\n const bVals = backend.texData.get(b.dataId).values as TypedArray;\n const [outValues, outShape] =\n cpuBitwiseAnd(a.shape, b.shape, aVals, bVals, a.dtype);\n\n const out = backend.makeTensorInfo(outShape, a.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 (shouldUsePackedProgram) {\n program = new BinaryOpPackedProgram(BITWISEAND, a.shape, b.shape, false);\n } else {\n program = new BinaryOpProgram(BITWISEAND_UNPACKED, a.shape, b.shape);\n }\n\n return backend.runWebGLProgram(program, [a, b], a.dtype);\n}\n\nexport const bitwiseAndConfig: KernelConfig = {\n kernelName: BitwiseAnd,\n backendName: 'webgl',\n kernelFunc: bitwiseAnd as unknown 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, BroadcastArgs, BroadcastArgsInputs, KernelConfig, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function broadcastArgs(args: {\n inputs: BroadcastArgsInputs,\n backend: MathBackendWebGL,\n}): TensorInfo {\n const {inputs, backend} = args;\n const {s0, s1} = inputs;\n\n const s0Vals = backend.readSync(s0.dataId) as TypedArray;\n const s1Vals = backend.readSync(s1.dataId) as TypedArray;\n\n const broadcastShape = backend_util.assertAndGetBroadcastShape(\n Array.from(s0Vals), Array.from(s1Vals));\n\n return backend.makeTensorInfo(\n [broadcastShape.length], 'int32', Int32Array.from(broadcastShape));\n}\n\nexport const broadcastArgsConfig: KernelConfig = {\n kernelName: BroadcastArgs,\n backendName: 'webgl',\n kernelFunc: broadcastArgs\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {NotEqual} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {notEqualImplCPU} from '../kernel_utils/shared';\n\nconst NOT_EQUAL = `return float(a != b);`;\n\nexport const notEqual = binaryKernelFunc(\n {opSnippet: NOT_EQUAL, cpuKernelImpl: notEqualImplCPU, dtype: 'bool'});\n\nexport const notEqualConfig: KernelConfig = {\n kernelName: NotEqual,\n backendName: 'webgl',\n kernelFunc: notEqual,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Real, RealInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function real(args: {inputs: RealInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n const inputData = backend.texData.get(input.dataId);\n\n return identity({inputs: {x: inputData.complexTensorInfos.real}, backend});\n}\n\nexport const realConfig: KernelConfig = {\n kernelName: Real,\n backendName: 'webgl',\n kernelFunc: real as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {UnaryOpProgram} from '../unaryop_gpu';\n\nconst TO_INT = `return float(int(x));`;\n\nexport function int(input: TensorInfo, backend: MathBackendWebGL): TensorInfo {\n const program = new UnaryOpProgram(input.shape, TO_INT);\n const output = backend.runWebGLProgram(program, [input], 'int32');\n return {dataId: output.dataId, shape: output.shape, dtype: output.dtype};\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport * as tf from '@tensorflow/tfjs-core';\nimport {BinaryInputs, Cast, CastAttrs, CastInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {castImplCPU} from '../kernel_utils/shared';\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 (backend.shouldExecuteOnCPU([x])) {\n const values = backend.texData.get(x.dataId).values as TypedArray;\n const [resultShape, resultType, resultData] =\n castImplCPU(values, x.shape, x.dtype, dtype);\n return backend.makeTensorInfo(resultShape, resultType, resultData);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class ClipProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n customUniforms = [\n {name: 'minVal', type: 'float' as UniformType},\n {name: 'maxVal', type: 'float' as UniformType}\n ];\n\n constructor(aShape: number[]) {\n this.outputShape = aShape;\n this.userCode = `\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class ClipPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n userCode: string;\n outputShape: number[];\n customUniforms = [\n {name: 'minVal', type: 'float' as UniformType},\n {name: 'maxVal', type: 'float' as UniformType}\n ];\n\n constructor(aShape: number[]) {\n this.outputShape = aShape;\n this.userCode = `\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ClipProgram} from '../clip_gpu';\nimport {ClipPackedProgram} from '../clip_packed_gpu';\n\nexport function clipByValue(args: {\n inputs: ClipByValueInputs,\n backend: MathBackendWebGL,\n attrs: ClipByValueAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {clipValueMin, clipValueMax} = attrs;\n\n let program;\n if (env().getBool('WEBGL_PACK_CLIP')) {\n program = new ClipPackedProgram(x.shape);\n } else {\n program = new ClipProgram(x.shape);\n }\n const customValues = [[clipValueMin], [clipValueMax]];\n return backend.runWebGLProgram(program, [x], x.dtype, customValues);\n}\n\nexport const clipByValueConfig: KernelConfig = {\n kernelName: ClipByValue,\n backendName: 'webgl',\n kernelFunc: clipByValue as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ComplexAbsProgram implements GPGPUProgram {\n variableNames = ['real', 'imag'];\n userCode: string;\n outputShape: number[];\n\n constructor(shape: number[]) {\n this.outputShape = shape;\n this.userCode = `\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ComplexAbs, ComplexAbsInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ComplexAbsProgram} from '../complex_abs_gpu';\n\n// Returns a TensorInfo with the complex shape and the dataId of the\n// underlying part. We need to do this because a reshaped complex tensor is\n// not reflected in its parts.\nfunction makeComplexComponentTensorInfo(\n complexTensor: TensorInfo, complexPart: TensorInfo): TensorInfo {\n return {\n dataId: complexPart.dataId,\n dtype: complexPart.dtype,\n shape: complexTensor.shape\n };\n}\n\nexport function complexAbs(\n args: {inputs: ComplexAbsInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const xData = backend.texData.get(x.dataId);\n\n const program = new ComplexAbsProgram(x.shape);\n const programInputs = [\n makeComplexComponentTensorInfo(x, xData.complexTensorInfos.real),\n makeComplexComponentTensorInfo(x, xData.complexTensorInfos.imag),\n ];\n\n return backend.runWebGLProgram(\n program, programInputs, programInputs[0].dtype);\n}\n\nexport const complexAbsConfig: KernelConfig = {\n kernelName: ComplexAbs,\n backendName: 'webgl',\n kernelFunc: complexAbs as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ConcatProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n // Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().\n constructor(shapes: Array<[number, number]>) {\n this.outputShape = backend_util.computeOutShape(shapes, 1 /* axis */);\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const offsets: number[] = new Array(shapes.length - 1);\n offsets[0] = shapes[0][1];\n for (let i = 1; i < offsets.length; i++) {\n offsets[i] = offsets[i - 1] + shapes[i][1];\n }\n\n const snippets = [`if (yC < ${offsets[0]}) setOutput(getT0(yR, yC));`];\n for (let i = 1; i < offsets.length; i++) {\n const shift = offsets[i - 1];\n snippets.push(\n `else if (yC < ${offsets[i]}) ` +\n `setOutput(getT${i}(yR, yC-${shift}));`);\n }\n const lastIndex = offsets.length;\n const lastShift = offsets[offsets.length - 1];\n snippets.push(`else setOutput(getT${lastIndex}(yR, yC-${lastShift}));`);\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${snippets.join('\\n ')}\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ConcatPackedProgram implements GPGPUProgram {\n variableNames: string[];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(shapes: number[][], axis: number) {\n this.outputShape = backend_util.computeOutShape(shapes, axis);\n const shape = this.outputShape;\n const rank = shape.length;\n const dtype = getCoordsDataType(rank);\n const coords = getChannels('coords', rank);\n const channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank);\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const offsets: number[] = new Array(shapes.length - 1);\n offsets[0] = shapes[0][axis];\n for (let i = 1; i < offsets.length; i++) {\n offsets[i] = offsets[i - 1] + shapes[i][axis];\n }\n\n const channel = channels[axis];\n const lastChannels = channels.slice(-2);\n const allChannels = channels.join();\n\n let getValueSnippet = `if (${channel} < ${offsets[0]}) {\n return getChannel(\n getT0(${allChannels}), vec2(${lastChannels.join()}));\n }`;\n for (let i = 1; i < offsets.length; i++) {\n const shift = offsets[i - 1];\n // Note: the >= comparison below may seem unnecessary given the check\n // above but is needed to workaround branch execution issues on some\n // devices. It makes all the conditions exclusive without relying on\n // execution order.\n getValueSnippet += `\n if (${channel} < ${offsets[i]} && ${channel} >= ${offsets[i - 1]}) {\n return getChannel(\n getT${i}(${shiftedChannels(channels, channel, shift)}),\n vec2(${shiftedChannels(lastChannels, channel, shift)}));\n }`;\n }\n const lastIndex = offsets.length;\n const shift = offsets[offsets.length - 1];\n getValueSnippet += `\n return getChannel(\n getT${lastIndex}(${shiftedChannels(channels, channel, shift)}),\n vec2(${shiftedChannels(lastChannels, channel, shift)}));`;\n\n this.userCode = `\n float getValue(${channels.map(x => 'int ' + x)}) {\n ${getValueSnippet}\n }\n\n void main() {\n ${dtype} coords = getOutputCoords();\n vec4 result = vec4(getValue(${coords}), 0., 0., 0.);\n\n ${coords[rank - 1]} = ${coords[rank - 1]} + 1;\n if (${coords[rank - 1]} < ${shape[rank - 1]}) {\n result.g = getValue(${coords});\n }\n\n ${coords[rank - 2]} = ${coords[rank - 2]} + 1;\n if (${coords[rank - 2]} < ${shape[rank - 2]}) {\n result.a = getValue(${coords});\n }\n\n ${coords[rank - 1]} = ${coords[rank - 1]} - 1;\n if (${coords[rank - 2]} < ${shape[rank - 2]} &&\n ${coords[rank - 1]} < ${shape[rank - 1]}) {\n result.b = getValue(${coords});\n }\n setOutput(result);\n }\n `;\n }\n}\n\n/**\n * Return an expression for coordinates into a vector where a given channel\n * will be offset by [shift].\n *\n * @param channels the channels to consider\n * @param channel the channel we want shifted\n * @param shift the amount to subtract from the channel.\n *\n * @returns a string of the form 'x, y-[shift], z' where any one channel can\n * have the shift applied.\n */\nfunction shiftedChannels(channels: string[], channel: string, shift: number) {\n const channelIdx = channels.indexOf(channel);\n const res = channels.map((c, idx) => {\n if (idx === channelIdx) {\n return `${c} - ${shift}`;\n } else {\n return c;\n }\n });\n return res.join();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Imag, ImagInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function imag(args: {inputs: ImagInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n const inputData = backend.texData.get(input.dataId);\n\n return identity({inputs: {x: inputData.complexTensorInfos.imag}, backend});\n}\n\nexport const imagConfig: KernelConfig = {\n kernelName: Imag,\n backendName: 'webgl',\n kernelFunc: imag as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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';\nimport {CLONE, UnaryOpProgram} from '../unaryop_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\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 // Keep only non-empty tensors (ignore tensors with 0 in their shape).\n const $inputs = inputs.filter(t => util.sizeFromShape(t.shape) > 0);\n\n const shouldPack: boolean = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') &&\n $inputs[0].shape.length > 1;\n\n if ($inputs.length === 1) {\n // Clone tensor.\n const program = shouldPack ?\n new UnaryOpProgram(inputs[0].shape, CLONE) :\n new UnaryOpPackedProgram(inputs[0].shape, CLONE);\n return backend.runWebGLProgram(program, inputs, dtype);\n }\n\n const maxTexturesInShader = env().getNumber('WEBGL_MAX_TEXTURES_IN_SHADER');\n if ($inputs.length > maxTexturesInShader) {\n const reducedInputs = [];\n for (let i = 0; i < $inputs.length; i += maxTexturesInShader) {\n const subArray = $inputs.slice(i, i + maxTexturesInShader);\n reducedInputs.push(concatImpl(subArray, axis, backend));\n }\n const result = concatImpl(reducedInputs, axis, backend);\n\n for (const i of reducedInputs) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return result;\n }\n\n if (shouldPack) {\n const program = new ConcatPackedProgram($inputs.map(t => t.shape), axis);\n return backend.runWebGLProgram(program, $inputs, dtype);\n }\n\n const {tensors2D, outShape} = computeTensors2D($inputs, axis, backend);\n const program =\n new ConcatProgram(tensors2D.map(t => t.shape as [number, number]));\n const result = backend.runWebGLProgram(program, tensors2D, dtype);\n\n tensors2D.forEach(r => backend.disposeIntermediateTensorInfo(r));\n const reshapedResult =\n reshape({inputs: {x: result}, attrs: {shape: outShape}, backend});\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n}\n\nfunction computeTensors2D(\n inputs: ConcatInputs, axis: number, backend: MathBackendWebGL) {\n // Any concat of n-dimensional tensors across any axis can be reduced to\n // a concatenation of two-dimensional tensors across the axis 1 by first\n // partitioning the axes of the original tensors into those less than the\n // axis to be concatenated and the rest. Then reshape the tensors\n // into a two-dimensional tensor by collapsing these two sets of axes and\n // concatenate the resulting matrices across the axis 1, finally reshaping\n // the result to have the proper shape.\n const outShape = backend_util.computeOutShape(inputs.map(t => t.shape), axis);\n const tensors2D = inputs.map(\n x => reshape({\n inputs: {x},\n attrs: {shape: [-1, util.sizeFromShape(x.shape.slice(axis))]},\n backend\n }));\n\n return {tensors2D, outShape};\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Concat, ConcatAttrs, ConcatInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {concatImpl} from './Concat_impl';\nimport {identity} from './Identity';\n\nexport function concat(\n args:\n {inputs: ConcatInputs, attrs: ConcatAttrs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, inputs[0].shape)[0];\n\n const shapes = inputs.map(t => t.shape);\n backend_util.assertParamsConsistent(shapes, $axis);\n\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 return concatImpl($inputs, $axis, backend);\n}\n\nexport const concatConfig: KernelConfig = {\n kernelName: Concat,\n backendName: 'webgl',\n kernelFunc: concat as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Conv2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivationWeights = false,\n hasLeakyreluAlpha = false) {\n this.outputShape = convInfo.outShape;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;\n const inputDepthVec4Remainder = convInfo.inChannels % 4;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n const channelDim = isChannelsLast ? 3 : 1;\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivationWeights) {\n activationSnippet = `float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyreluAlpha) {\n activationSnippet = `float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `\n float activation(float x) {\n ${activation}\n }\n `;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivationWeights) {\n this.variableNames.push('preluActivationWeights');\n }\n\n if (hasLeakyreluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${channelDim}];\n\n ivec2 xRCCorner =\n ivec2(coords[${rowDim}], coords[${colDim}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${isChannelsLast}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${inputDepthVec4Remainder === 1}) {\n\n if (${isChannelsLast}) {\n dotProd +=\n getX(batch, xR, xC, ${inputDepthNearestVec4}) *\n getW(wR, wC, ${inputDepthNearestVec4}, d2);\n } else {\n dotProd +=\n getX(batch, ${inputDepthNearestVec4}, xR, xC) *\n getW(wR, wC, ${inputDepthNearestVec4}, d2);\n }\n\n } else if (${inputDepthVec4Remainder === 2}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 1, d2)\n );\n\n if (${isChannelsLast}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${inputDepthNearestVec4}, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${inputDepthVec4Remainder === 3}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 1, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 2, d2)\n );\n\n if (${isChannelsLast}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 1),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${inputDepthNearestVec4}, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 1, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\n }\n `;\n }\n}\n\nexport class Conv3DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.outShape;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;\n const inputDepthVec4Remainder = convInfo.inChannels % 4;\n\n this.userCode = `\n const ivec3 strides = ivec3(${strideDepth}, ${strideHeight}, ${\n strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${filterDepth}; wF++) {\n int xF = xFCorner + wF * ${dilationDepth};\n\n if (xF < 0 || xF >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${inputDepthVec4Remainder === 1}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}) *\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2);\n } else if (${inputDepthVec4Remainder === 2}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${inputDepthVec4Remainder === 3}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n import {backend_util, util} from '@tensorflow/tfjs-core';\n\n import {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\n export class Conv2DPackedProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n enableShapeUniforms: boolean;\n customUniforms = [\n {name: 'pads', type: 'ivec2' as const },\n {name: 'strides', type: 'ivec2' as const },\n {name: 'dilations', type: 'ivec2' as const },\n {name: 'inDims', type: 'ivec2' as const },\n ];\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 this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n const padLeft = convInfo.padInfo.left;\n const strideWidth = convInfo.strideWidth;\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 mainLoop += `\n for (int r = 0; r < ${filterHeight}; r++) {\n for (int d1 = 0; d1 < ${convInfo.inChannels}; d1 += 2) {\n `;\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 * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n `;\n\n for (let texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {\n const colIndex = texelC * 2;\n\n mainLoop += `\n xC = xCCorner + ${colIndex * dilationWidth};\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 < inDims[1] && 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 >= inDims[1]) {\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 && colIndex > 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 < inDims[1]) {\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 >= inDims[1]) {\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 < inDims[1] && xTexelC${colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\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 (colIndex + 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 + imod(pads[1], 2) + ${nextTexelOffset};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && 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 >= inDims[1]) {\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 < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${colIndex + 1} = vec4(previous.zw, xTexelC${\n colIndex + 1}.xy);\n } else {\n xC${colIndex + 1} = vec4(0.0, 0.0, xTexelC${\n colIndex + 1}.xy);\n }\n `;\n } else {\n mainLoop += `\n xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${\n colIndex + 1}.xy);\n `;\n }\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 < inDims[1] && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\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 (colIndex < 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 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && 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 >= inDims[1]) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && 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 >= inDims[1]) {\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 (colIndex + 1 < filterWidth) {\n mainLoop += `\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\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 < inDims[1] && xTexelC${colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\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 (colIndex + 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, ${colIndex}, d1, d2);\n dotProd += xC${colIndex}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${convInfo.inChannels}) {\n dotProd += xC${colIndex}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `;\n\n if (colIndex + 1 < filterWidth) {\n mainLoop += `\n wTexel = getW(r, ${colIndex + 1}, d1, d2);\n dotProd += xC${colIndex + 1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${convInfo.inChannels}) {\n dotProd += xC${colIndex + 1}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `;\n }\n }\n }\n mainLoop += `\n }\n `;\n mainLoop += `\n }\n `;\n mainLoop += `\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 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 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 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, useShapeUniforms} 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 enableShapeUniforms: boolean;\n customUniforms = [\n {name: 'inputShape', type: 'ivec4' as const },\n {name: 'pad', type: 'ivec2' as const },\n {name: 'stride', type: 'ivec2' as const },\n {name: 'dilation', type: 'ivec2' as const },\n {name: 'inChannels', type: 'int' as const },\n {name: 'itemsPerBlockRow', type: 'int' as const },\n {name: 'outWidth', type: 'int' as const },\n ];\n\n constructor(outputShape: number[], convInfo: backend_util.Conv2DInfo) {\n this.outputShape = outputShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n const {dataFormat} = convInfo;\n const glsl = getGlslDifferences();\n const isChannelsLast = dataFormat === 'channelsLast';\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n\n const boundsCheckingSnippet = this.enableShapeUniforms ?\n 'if(blockIndex < outShape[2] && pos < outShape[1]) {' :\n `if(blockIndex < ${outputShape[2]} && pos < ${outputShape[1]}) {`;\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.z + ${col};\n pos = rc.y + ${row};\n\n ${boundsCheckingSnippet}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${rowDim}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${colDim}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${isChannelsLast}) {\n innerDims = vec2(d1, ch);\n result[${row * 2 + col}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${row * 2 + col}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;\n }\n }\n\n this.userCode = `\n void main() {\n ivec3 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, TensorInfo, util} from '@tensorflow/tfjs-core';\n\n// import {assertAndGetBroadcastShape} from\n// '../../../tfjs-core/src/ops/broadcast_util';\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// Both conv2dByMatMul and conv2dWithIm2Row fuse height and width into one\n// dimension to compute batchMatMul, so bias and activation weights are also\n// supposed to fuse the two dimensions into one.\n//\n// This function computes the target shape for fusing height and width\n// dimensions. Returning null means the shape is already compatible.\n//\n// Even though the bias is not supposed to be a 3-D or a 4-D (including\n// batch) tensor and PReLU activiation weights is not supposed to be a 4-D\n// tensor, we still need to support them, because we haven't disabled\n// them for NHWC format.\n// https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/conv2d.ts#L181-L196\nfunction getShapeForBatchMatMul(\n shape: number[], isChannelsLast: boolean): number[] {\n const length = shape.length;\n if (length >= 3) {\n return isChannelsLast ?\n [\n ...shape.slice(0, -3) /* batch */,\n shape[length - 3] * shape[length - 2] /* height * width */,\n shape[length - 1] /* channel */\n ] :\n [\n ...shape.slice(0, -3) /* batch */, shape[length - 3] /* channel */,\n shape[length - 2] * shape[length - 1] /* height * width */\n ];\n } else if (!isChannelsLast && length === 1 && shape[0] > 1) {\n return [shape[0], 1];\n } else {\n return null;\n }\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 if (preluActivationWeights != null) {\n const targetShape =\n getShapeForBatchMatMul(preluActivationWeights.shape, isChannelsLast);\n if (targetShape != null) {\n preluActivationWeights = reshape({\n inputs: {x: preluActivationWeights},\n backend,\n attrs: {shape: targetShape}\n });\n intermediates.push(preluActivationWeights);\n }\n }\n\n if (bias != null) {\n const targetShape = getShapeForBatchMatMul(bias.shape, isChannelsLast);\n if (targetShape != null) {\n bias = reshape({inputs: {x: bias}, backend, attrs: {shape: targetShape}});\n intermediates.push(bias);\n }\n }\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\n // The algorithm in the if condition assumes (1) the output will be packed,\n // (2) x is packed, (3) x isChannelsLast, (4) x's packed texture is already\n // on GPU, (5) col is odd, (6) the width, height and inChannels are the same\n // for xTexData.shape and xShape.\n const canOptimize = !batchMatMulWillBeUnpacked && xTexData.isPacked &&\n isChannelsLast && xTexData.texture != null && xShape[2] % 2 !== 0 &&\n util.arraysEqual(xTexData.shape.slice(-3), xShape.slice(-3));\n\n if (canOptimize) {\n // We avoid expensive packed 2x2 reshape by padding col count to next,\n // even number. When col 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 next even col. We make the odd-cols tensor to look like\n // even-cols tensor before the operation and, after the batchMatMul,\n // fix the even-cols result to have odd number of cols.\n const targetShape = xShape[0] * xShape[1] * (xShape[2] + 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 col count, after batchMatMul->...->compileProgram leads to\n // invalid col 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 col 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 } else {\n const numCols = convInfo.outHeight * convInfo.outWidth;\n const xReshaped = reshape({\n inputs: {x},\n backend,\n attrs: {\n shape: isChannelsLast ?\n [convInfo.batchSize, numCols, convInfo.inChannels] :\n [convInfo.batchSize, convInfo.inChannels, numCols]\n }\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: isChannelsLast ? xReshaped : filterReshaped,\n b: isChannelsLast ? filterReshaped : xReshaped,\n transposeA: !isChannelsLast,\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 }\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 = [convInfo.batchSize, sharedDim, numCols];\n const transposeA = true;\n const transposeB = false;\n\n const intermediates: TensorInfo[] = [];\n\n if (preluActivationWeights != null) {\n const targetShape =\n getShapeForBatchMatMul(preluActivationWeights.shape, isChannelsLast);\n if (targetShape != null) {\n preluActivationWeights = reshape({\n inputs: {x: preluActivationWeights},\n backend,\n attrs: {shape: targetShape}\n });\n intermediates.push(preluActivationWeights);\n }\n }\n\n if (bias != null) {\n const targetShape = getShapeForBatchMatMul(bias.shape, isChannelsLast);\n if (targetShape != null) {\n bias = reshape({inputs: {x: bias}, backend, attrs: {shape: targetShape}});\n intermediates.push(bias);\n }\n }\n\n const w2Row = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, sharedDim, util.sizeFromShape(filter.shape) / sharedDim]}\n });\n intermediates.push(w2Row);\n\n const im2ColProgram = new Im2ColPackedProgram(x2ColShape, convInfo);\n const customValues = [\n x.shape, [convInfo.padInfo.top, convInfo.padInfo.left],\n [convInfo.strideHeight, convInfo.strideWidth],\n [convInfo.dilationHeight, convInfo.dilationWidth], [convInfo.inChannels],\n [convInfo.filterWidth * convInfo.inChannels], [convInfo.outWidth]\n ];\n const im2Col =\n backend.runWebGLProgram(im2ColProgram, [x], 'float32', customValues);\n const im2ColReshaped =\n reshape({inputs: {x: im2Col}, backend, attrs: {shape: x2ColShape}});\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 isChannelsLast ? im2ColReshaped.shape as [number, number, number] :\n w2Row.shape as [number, number, number],\n isChannelsLast ? w2Row.shape as [number, number, number] :\n im2ColReshaped.shape as [number, number, number],\n isChannelsLast ? [convInfo.batchSize, numCols, convInfo.outChannels] :\n [convInfo.batchSize, convInfo.outChannels, numCols],\n transposeA, transposeB, hasBias, fusedActivation,\n hasPreluActivationWeights, hasLeakyreluAlpha);\n const inputs: TensorInfo[] =\n isChannelsLast ? [im2ColReshaped, w2Row] : [w2Row, im2ColReshaped];\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 unknown as 'float32',\n 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n const product = backend.runWebGLProgram(matmulProgram, inputs, 'float32');\n const out = reshape(\n {inputs: {x: product}, backend, attrs: {shape: convInfo.outShape}});\n\n intermediates.push(product);\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2D, Conv2DAttrs, Conv2DInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DProgram} from '../conv_gpu';\nimport {Conv2DPackedProgram} from '../conv_packed_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 (convInfo.strideWidth <= 2 && $dataFormat === 'channelsLast'\n && env().getBool('WEBGL_EXP_CONV')\n ) {\n const program = new Conv2DPackedProgram(convInfo);\n const customValues = [\n [convInfo.padInfo.top, convInfo.padInfo.left],\n [convInfo.strideHeight, convInfo.strideWidth],\n [convInfo.dilationHeight, convInfo.dilationWidth],\n [convInfo.inHeight, convInfo.inWidth]\n ];\n out =\n backend.runWebGLProgram(program, [x, filter], 'float32', customValues);\n } else if (env().getBool('WEBGL_CONV_IM2COL')) {\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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Conv2DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n ${isChannelsLast?\n `float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);` :\n `float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);`}\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class Conv2DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n const channelDim = isChannelsLast ? 3 : 1;\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${channelDim}];\n\n ivec2 dyCorner = ivec2(coords[${rowDim}], coords[${colDim}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {\n\n if (${isChannelsLast}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class Conv3DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n this.userCode = `\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yF = 0; yF < ${convInfo.outDepth}; yF++) {\n int xF = wF + yF * ${strideDepth} - ${padFront};\n\n if (xF < 0 || xF >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class Conv3DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n\n const padFront = filterDepth - 1 - convInfo.padInfo.front;\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${filterDepth}; wF++) {\n float dyF = float(dyFCorner + wF) / ${strideDepth}.0;\n\n if (dyF < 0.0 || dyF >= ${convInfo.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${filterDepth} - 1 - wF;\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DDerFilterProgram} from '../conv_backprop_gpu';\n\nexport function conv2DBackpropFilter(args: {\n inputs: Conv2DBackpropFilterInputs,\n attrs: Conv2DBackpropFilterAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, dataFormat, dimRoundingMode, filterShape} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad, dimRoundingMode, false /* depthwise */,\n $dataFormat);\n\n const program = new Conv2DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const conv2DBackpropFilterConfig: KernelConfig = {\n kernelName: Conv2DBackpropFilter,\n backendName: 'webgl',\n kernelFunc: conv2DBackpropFilter as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\nexport class Conv2DDerInputPackedProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n enableShapeUniforms: boolean;\n customUniforms = [\n {name: 'strides', type: 'vec2' as const },\n ];\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\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\n ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n vec4 result = vec4(0.);\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / strides[0];\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int wCPerm = ${filterWidth} - 1 - wC;\n\n float dyC = float(dyCCorner + wC) / strides[1];\n bool idyCVal = (dyC >= 0.0) && (dyC < ${convInfo.outWidth}.0)\n && (fract(dyC) == 0.0);\n int idyC = int(dyC);\n\n float dyC2 = float(dyCCorner + wC + 1) / strides[1];\n bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${convInfo.outWidth}.0)\n && (fract(dyC2) == 0.0);\n int idyC2 = int(dyC2);\n\n if (idyCVal && idyCVal2) {\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\n dySample : getDy(batch, idyR, idyC2, d2);\n\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n\n dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample2.xy : dySample2.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal) {\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal2) {\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC2, d2);\n vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n }\n }\n }\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs, env, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DDerInputProgram} from '../conv_backprop_gpu';\nimport {Conv2DDerInputPackedProgram} from '../conv_backprop_packed_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 if (env().getBool('WEBGL_PACK_CONV2DTRANSPOSE') &&\n $dataFormat === 'channelsLast') {\n const customValues = [\n [convInfo.strideHeight, convInfo.strideWidth],\n ];\n const program = new Conv2DDerInputPackedProgram(convInfo);\n return backend.runWebGLProgram(\n program, [dy, filter], 'float32', customValues);\n } else {\n const program = new Conv2DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n }\n}\n\nexport const conv2DBackpropInputConfig: KernelConfig = {\n kernelName: Conv2DBackpropInput,\n backendName: 'webgl',\n kernelFunc: conv2DBackpropInput as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\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\nconst COS_PACKED = `\n vec4 result = cos(x);\n bvec4 isNaN = isnan(x);\n ${CHECK_NAN_SNIPPET_PACKED}\n return result;\n`;\n\nexport const cos =\n unaryKernelFunc({opSnippet: COS, packedOpSnippet: COS_PACKED});\n\nexport const cosConfig: KernelConfig = {\n kernelName: Cos,\n backendName: 'webgl',\n kernelFunc: cos,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cosh, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst COSH = `\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n`;\n\nexport const cosh = unaryKernelFunc({opSnippet: COSH});\n\nexport const coshConfig: KernelConfig = {\n kernelName: Cosh,\n backendName: 'webgl',\n kernelFunc: cosh,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class CropAndResizeProgram implements GPGPUProgram {\n variableNames = ['Image', 'Boxes', 'BoxInd'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n imageShape: [number, number, number, number], boxShape: [number, number],\n cropSize: [number, number], method: 'bilinear'|'nearest',\n extrapolationValue: number) {\n const [batch, imageHeight, imageWidth, depth] = imageShape;\n const [numBoxes, ] = boxShape;\n const [cropHeight, cropWidth] = cropSize;\n this.outputShape = [numBoxes, cropHeight, cropWidth, depth];\n const methodId = method === 'bilinear' ? 1 : 0;\n\n const [inputHeightFloat, inputWidthFloat] =\n [`${imageHeight - 1}.0`, `${imageWidth - 1}.0`];\n\n const [heightRatio, heightScale, inY] = cropHeight > 1 ?\n [\n `${(imageHeight - 1) / (cropHeight - 1)}`,\n '(y2-y1) * height_ratio',\n `y1*${inputHeightFloat} + float(y)*(height_scale)`,\n ] :\n [\n '0.0',\n '0.0',\n `0.5 * (y1+y2) * ${inputHeightFloat}`,\n ];\n const [widthRatio, widthScale, inX] = cropWidth > 1 ?\n [\n `${(imageWidth - 1) / (cropWidth - 1)}`,\n '(x2-x1) * width_ratio',\n `x1*${inputWidthFloat} + float(x)*(width_scale)`,\n ] :\n [\n '0.0',\n '0.0',\n `0.5 * (x1+x2) * ${inputWidthFloat}`,\n ];\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op_gpu.cu.cc\n this.userCode = `\n const float height_ratio = float(${heightRatio});\n const float width_ratio = float(${widthRatio});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${batch}) {\n return;\n }\n\n float height_scale = ${heightScale};\n float width_scale = ${widthScale};\n\n float in_y = ${inY};\n if( in_y < 0.0 || in_y > ${inputHeightFloat} ) {\n setOutput(float(${extrapolationValue}));\n return;\n }\n float in_x = ${inX};\n if( in_x < 0.0 || in_x > ${inputWidthFloat} ) {\n setOutput(float(${extrapolationValue}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${methodId} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CropAndResizeProgram} from '../crop_and_resize_gpu';\n\nexport const cropAndResize = (args: {\n inputs: CropAndResizeInputs,\n backend: MathBackendWebGL,\n attrs: CropAndResizeAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {image, boxes, boxInd} = inputs;\n const {cropSize, method, extrapolationValue} = attrs;\n\n const program = new CropAndResizeProgram(\n image.shape as [number, number, number, number],\n boxes.shape as [number, number], cropSize, method, extrapolationValue);\n return backend.runWebGLProgram(program, [image, boxes, boxInd], 'float32');\n};\n\nexport const cropAndResizeConfig: KernelConfig = {\n kernelName: CropAndResize,\n backendName: 'webgl',\n kernelFunc: cropAndResize as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport enum CumOpType {\n Prod = '*',\n Sum = '+',\n}\n\nexport class CumProgram implements GPGPUProgram {\n variableNames = ['x'];\n userCode: string;\n customUniforms = [{name: 'index', type: 'float' as UniformType}];\n\n constructor(\n public op: CumOpType, public outputShape: number[], exclusive: boolean,\n reverse: boolean) {\n const rank = this.outputShape.length;\n const initVal = this.op === CumOpType.Prod ? '1.0' : '0.0';\n const val =\n exclusive ? initVal : `getX(${getCoords(rank, 'coords', this.op)})`;\n const length = this.outputShape[this.outputShape.length - 1];\n let condition = '';\n let idxString = '';\n // When exclusive is set, the cum 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', this.op)};\n float val = ${val};\n int pow2 = int(pow(2.0, index));\n if (${condition}) {\n int idx = ${idxString};\n ${getFinalCoord(rank, 'coords', this.op)} = idx;\n val ${this.op}= getX(${getCoords(rank, 'coords', this.op)});\n }\n setOutput(val);\n }\n `;\n }\n}\n\nfunction getCoords(rank: number, name: string, op: CumOpType): 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 new Error(`Cumulative ${op} for rank ${rank} is not yet supported`);\n }\n}\n\nfunction getFinalCoord(rank: number, name: string, op: CumOpType): 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 new Error(`Cumulative ${op} for rank ${rank} is not yet supported`);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CumOpType, CumProgram} from '../cum_gpu';\n\nimport {identity} from './Identity';\nimport {transpose} from './Transpose';\n\nexport function cumImpl(\n op: CumOpType, x: TensorInfo, backend: MathBackendWebGL, axis: number,\n exclusive: boolean, reverse: boolean): TensorInfo {\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 cumprod 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 cum parallel algorithm, inspired by:\n // https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-39-parallel-prefix-sum-scan-cuda\n // Note: although the algorithm is called sum, it works for any associtative\n // operator with an identity.\n\n for (let i = 0; i <= Math.ceil(Math.log2(size)) - 1; i++) {\n const program = new CumProgram(op, 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 cum, shift the end result in the direction of product or sum\n // and add 1 for product or 0 for sum to the front index.\n if (exclusive) {\n const program = new CumProgram(op, 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","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cumprod, CumprodAttrs, CumprodInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CumOpType} from '../cum_gpu';\nimport {cumImpl} from './Cum_impl';\n\nexport function cumprod(args: {\n inputs: CumprodInputs,\n backend: MathBackendWebGL,\n attrs: CumprodAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n\n return cumImpl(CumOpType.Prod, x, backend, axis, exclusive, reverse);\n}\n\nexport const cumprodConfig: KernelConfig = {\n kernelName: Cumprod,\n backendName: 'webgl',\n kernelFunc: cumprod as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cumsum, CumsumAttrs, CumsumInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CumOpType} from '../cum_gpu';\nimport {cumImpl} from './Cum_impl';\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 return cumImpl(CumOpType.Sum, x, backend, axis, exclusive, reverse);\n}\n\nexport const cumsumConfig: KernelConfig = {\n kernelName: Cumsum,\n backendName: 'webgl',\n kernelFunc: cumsum as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs, KernelConfig, KernelFunc, Rank, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthToSpaceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n blockSize: number;\n dataFormat: string;\n\n constructor(\n outputShape: number[], blockSize: number, dataFormat: 'NHWC'|'NCHW') {\n this.outputShape = outputShape;\n this.blockSize = blockSize;\n this.dataFormat = dataFormat;\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${blockSize};\n int offset_h = imod(h, ${blockSize});\n int in_w = w / ${blockSize};\n int offset_w = imod(w, ${blockSize});\n int offset_d = (offset_h * ${blockSize} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `;\n }\n\n private getHeightCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[1]`;\n } else {\n return `coords[2]`;\n }\n }\n\n private getWidthCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[2]`;\n } else {\n return `coords[3]`;\n }\n }\n\n private getDepthCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[3]`;\n } else {\n return `coords[1]`;\n }\n }\n\n private getOutputDepthSize(): number {\n if (this.dataFormat === 'NHWC') {\n return this.outputShape[3];\n } else {\n return this.outputShape[1];\n }\n }\n\n private getInputSamplingString(): string {\n if (this.dataFormat === 'NHWC') {\n return `getX(b, in_h, in_w, in_d)`;\n } else {\n return `getX(b, in_d, in_h, in_w)`;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs, KernelConfig, KernelFunc, TensorInfo} 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 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\nexport class DepthwiseConv2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n enableShapeUniforms: boolean;\n customUniforms = [\n {name: 'pads', type: 'ivec2' as const },\n {name: 'strides', type: 'ivec2' as const },\n {name: 'dilations', type: 'ivec2' as const },\n {name: 'inDims', type: 'ivec2' as const },\n ];\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 this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n\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 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 * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\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, useShapeUniforms} 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 enableShapeUniforms: boolean;\n customUniforms = [\n {name: 'pads', type: 'ivec2' as const },\n {name: 'strides', type: 'ivec2' as const },\n {name: 'dilations', type: 'ivec2' as const },\n {name: 'inDims', type: 'ivec2' as const },\n ];\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 this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n const padLeft = convInfo.padInfo.left;\n const strideWidth = convInfo.strideWidth;\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 mainLoop += `\n for (int r = 0; r < ${filterHeight}; r++) {\n `;\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 * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n `;\n\n for (let texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {\n const colIndex = texelC * 2;\n\n mainLoop += `\n xC = xCCorner + ${colIndex * dilationWidth};\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 < inDims[1] && 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 >= inDims[1]) {\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 && colIndex > 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 < inDims[1]) {\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 >= inDims[1]) {\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 < inDims[1] && xTexelC${colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\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 (colIndex + 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 + imod(pads[1], 2) + ${nextTexelOffset};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && 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 >= inDims[1]) {\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 < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${colIndex + 1} = vec4(previous.zw, xTexelC${\n colIndex + 1}.xy);\n } else {\n xC${colIndex + 1} = vec4(0.0, 0.0, xTexelC${\n colIndex + 1}.xy);\n }\n `;\n } else {\n mainLoop += `\n xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${\n colIndex + 1}.xy);\n `;\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 < inDims[1] && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\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 (colIndex < 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 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && 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 >= inDims[1]) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && 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 >= inDims[1]) {\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 (colIndex + 1 < filterWidth) {\n mainLoop += `\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\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 < inDims[1] && xTexelC${colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\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 (colIndex + 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, ${colIndex}, d1, q);\n dotProd += xC${colIndex} * vec4(wTexel.xz, wTexel.xz);\n `;\n\n if (colIndex + 1 < filterWidth) {\n mainLoop += `\n wTexel = getW(r, ${colIndex + 1}, d1, q);\n dotProd += xC${colIndex + 1} * vec4(wTexel.xz, wTexel.xz);\n `;\n }\n }\n }\n mainLoop += `\n }\n `;\n mainLoop += `\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 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 int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${mainLoop}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs, env, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DProgram} from '../conv_gpu_depthwise';\nimport {DepthwiseConvPacked2DProgram} from '../conv_packed_gpu_depthwise';\n\nexport function depthwiseConv2dNative(args: {\n inputs: DepthwiseConv2dNativeInputs,\n attrs: DepthwiseConv2dNativeAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations, dimRoundingMode} = attrs;\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n let program: DepthwiseConv2DProgram|DepthwiseConvPacked2DProgram;\n if (env().getBool('WEBGL_PACK_DEPTHWISECONV') && convInfo.strideWidth <= 2 &&\n convInfo.outChannels / convInfo.inChannels === 1) {\n program = new DepthwiseConvPacked2DProgram(convInfo);\n } else {\n program = new DepthwiseConv2DProgram(convInfo);\n }\n const customValues = [\n [convInfo.padInfo.top, convInfo.padInfo.left],\n [convInfo.strideHeight, convInfo.strideWidth],\n [convInfo.dilationHeight, convInfo.dilationWidth],\n [convInfo.inHeight, convInfo.inWidth]\n ];\n return backend.runWebGLProgram(program, [x, filter], 'float32', customValues);\n}\n\nexport const depthwiseConv2dNativeConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNative,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNative as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConv2DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${channelMul} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class DepthwiseConv2DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${channelMul}; dm++) {\n int d2 = d1 * ${channelMul} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DDerFilterProgram} from '../conv_backprop_gpu_depthwise';\n\nexport function depthwiseConv2dNativeBackpropFilter(args: {\n inputs: DepthwiseConv2dNativeBackpropFilterInputs,\n attrs: DepthwiseConv2dNativeBackpropFilterAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, dilations, pad, dimRoundingMode, filterShape} = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const program = new DepthwiseConv2DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const depthwiseConv2dNativeBackpropFilterConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropFilter,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNativeBackpropFilter as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DiagProgram implements GPGPUProgram {\n variableNames = ['X'];\n outputShape: number[];\n userCode: string;\n\n constructor(size: number) {\n this.outputShape = [size, size];\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Diag, DiagInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DiagProgram} from '../diag_gpu';\nimport {reshape} from './Reshape';\n\nexport function diag(args: {inputs: DiagInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const outShape = [...x.shape, ...x.shape];\n const xSize = util.sizeFromShape(x.shape);\n\n const flat = reshape({inputs: {x}, backend, attrs: {shape: [xSize]}});\n\n const program = new DiagProgram(xSize);\n const res = backend.runWebGLProgram(program, [flat], flat.dtype);\n\n const out = reshape({inputs: {x: res}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo(flat);\n backend.disposeIntermediateTensorInfo(res);\n\n return out;\n}\n\nexport const diagConfig: KernelConfig = {\n kernelName: Diag,\n backendName: 'webgl',\n kernelFunc: diag as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Dilation2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.outShape;\n\n const {\n inHeight,\n inWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth\n } = convInfo;\n\n const {top: padTop, left: padLeft} = padInfo;\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${filterHeight}; h++) {\n int hIn = hBeg + h * ${dilationHeight};\n\n if (hIn >= 0 && hIn < ${inHeight}) {\n for (int w = 0; w < ${filterWidth}; w++) {\n int wIn = wBeg + w * ${dilationWidth};\n\n if (wIn >= 0 && wIn < ${inWidth}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Dilation2D, Dilation2DAttrs, Dilation2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Dilation2DProgram} from '../dilation_gpu';\nimport {reshape} from './Reshape';\n\nexport function dilation2D(args: {\n inputs: Dilation2DInputs,\n attrs: Dilation2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n const convInfo = backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n let out: TensorInfo;\n\n const program = new Dilation2DProgram(convInfo);\n out = backend.runWebGLProgram(program, [x, filter], 'float32');\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n backend.disposeIntermediateTensorInfo(out);\n\n return outReshaped;\n}\n\nexport const dilation2DConfig: KernelConfig = {\n kernelName: Dilation2D,\n backendName: 'webgl',\n kernelFunc: dilation2D as unknown 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 >= 0.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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Erf, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../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 {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {expImplCPU} from '../kernel_utils/shared';\n\nexport const EXP = CHECK_NAN_SNIPPET_UNARY + `\n return exp(x);\n`;\n\nconst EXP_PACKED = `\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\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 exp = unaryKernelFunc({\n opSnippet: EXP,\n packedOpSnippet: EXP_PACKED,\n cpuKernelImpl: expImplCPU,\n dtype: 'float32',\n});\n\nexport const expConfig: KernelConfig = {\n kernelName: Exp,\n backendName: 'webgl',\n kernelFunc: exp as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class FFTProgram implements GPGPUProgram {\n variableNames = ['real', 'imag'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n component: 'real'|'imag', inputShape: [number, number],\n inverse: boolean) {\n const innerDim = inputShape[1];\n this.outputShape = inputShape;\n\n const exponentMultiplierSnippet =\n inverse ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`;\n const resultDenominator = inverse ? `${innerDim}.0` : '1.0';\n\n let opString: string;\n if (component === 'real') {\n opString = 'return real * expR - imag * expI;';\n } else if (component === 'imag') {\n opString = 'return real * expI + imag * expR;';\n } else {\n throw new Error(\n `FFT component must be either \"real\" or \"imag\", got ${component}.`);\n }\n\n this.userCode = `\n const float exponentMultiplier = ${exponentMultiplierSnippet};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${opString}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${innerDim});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${innerDim}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${resultDenominator};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FFTProgram} from '../fft_gpu';\n\nimport {complex} from './Complex';\nimport {reshape} from './Reshape';\n\nexport function fftImpl(\n x: TensorInfo, inverse: boolean, backend: MathBackendWebGL): TensorInfo {\n const xData = backend.texData.get(x.dataId);\n\n const inputSize = util.sizeFromShape(x.shape);\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = x.shape[x.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape(\n {inputs: {x}, backend, attrs: {shape: [batch, innerDimensionSize]}});\n\n const xShape = input2D.shape as [number, number];\n const realProgram = new FFTProgram('real', xShape, inverse);\n const imagProgram = new FFTProgram('imag', xShape, inverse);\n\n const inputs = [\n {\n dataId: xData.complexTensorInfos.real.dataId,\n dtype: xData.complexTensorInfos.real.dtype,\n shape: xShape\n },\n {\n dataId: xData.complexTensorInfos.imag.dataId,\n dtype: xData.complexTensorInfos.imag.dtype,\n shape: xShape\n }\n ];\n\n const realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');\n const imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');\n\n const complexOutput =\n complex({inputs: {real: realPart, imag: imagPart}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(imagPart);\n\n const complexOutputReshaped =\n reshape({inputs: {x: complexOutput}, backend, attrs: {shape: x.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(complexOutput);\n return complexOutputReshaped;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FFT, FFTInputs, KernelConfig, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {fftImpl} from './FFT_impl';\n\nexport function fft(args: {inputs: FFTInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n return fftImpl(input, false /* inverse */, backend);\n}\n\nexport const fftConfig: KernelConfig = {\n kernelName: FFT,\n backendName: 'webgl',\n kernelFunc: fft\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class FillProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n customUniforms = [{name: 'value', type: 'float' as UniformType}];\n\n constructor(shape: number[], value: number) {\n this.variableNames = ['x'];\n this.outputShape = shape;\n\n this.userCode = `\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Fill, FillAttrs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FillProgram} from '../fill_gpu';\n\nexport function fill(args: {backend: MathBackendWebGL, attrs: FillAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {shape, value} = attrs;\n let {dtype} = attrs;\n\n dtype = dtype || util.inferDtype(value);\n\n if (dtype === 'string') {\n // String type should be handled in CPU memory.\n const values = util.getArrayFromDType(dtype, util.sizeFromShape(shape));\n values.fill(value as string);\n return backend.makeTensorInfo(shape, dtype, values);\n } else {\n const program = new FillProgram(shape, value as number);\n const customValues = [[value as number]];\n return backend.runWebGLProgram(program, [], dtype, customValues);\n }\n}\n\nexport const fillConfig: KernelConfig = {\n kernelName: Fill,\n backendName: 'webgl',\n kernelFunc: fill as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class FlipLeftRightProgram implements GPGPUProgram {\n variableNames = ['Image'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(imageShape: [number, number, number, number]) {\n const imageWidth = imageShape[2];\n this.outputShape = imageShape;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${imageWidth} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${imageWidth}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Tensor4D} from '@tensorflow/tfjs-core';\nimport {FlipLeftRight, FlipLeftRightInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FlipLeftRightProgram} from '../flip_left_right_gpu';\n\nexport const flipLeftRightConfig: KernelConfig = {\n kernelName: FlipLeftRight,\n backendName: 'webgl',\n kernelFunc: ({inputs, backend}) => {\n const {image} = inputs as FlipLeftRightInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n const program = new FlipLeftRightProgram((image as Tensor4D).shape);\n const output = webglBackend.runWebGLProgram(program, [image], image.dtype);\n return output;\n }\n};\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Floor, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {floorImplCPU} from '../kernel_utils/shared';\n\nconst FLOOR = `return floor(x);`;\n\nexport const floor = unaryKernelFunc(\n {opSnippet: FLOOR, packedOpSnippet: FLOOR, cpuKernelImpl: floorImplCPU});\n\nexport const floorConfig: KernelConfig = {\n kernelName: Floor,\n backendName: 'webgl',\n kernelFunc: floor,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FloorDiv, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// We use native integer division to deal with floating point imprecision. Since\n// we implement floor division and glsl implements truncated division, we\n// correct for this by subtracting 1 from result when the result is negative and\n// there is a remainder.\nconst INT_DIV = `\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n`;\n\nconst INT_DIV_PACKED = `\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n`;\n\nexport const floorDiv = binaryKernelFunc(\n {opSnippet: INT_DIV, packedOpSnippet: INT_DIV_PACKED, dtype: 'int32'});\n\nexport const floorDivConfig: KernelConfig = {\n kernelName: FloorDiv,\n backendName: 'webgl',\n kernelFunc: floorDiv as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from '../../glsl_version';\nimport {GPGPUProgram} from '../../gpgpu_math';\n\nexport class FromPixelsProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n const [height, width, ] = outputShape;\n this.outputShape = outputShape;\n this.userCode = `\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${width}.0, ${height}.0);\n\n vec4 values = ${glsl.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from '../../glsl_version';\nimport {GPGPUProgram} from '../../gpgpu_math';\n\nexport class FromPixelsPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = false;\n packedOutput = true;\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n const [height, width, ] = outputShape;\n this.outputShape = outputShape;\n this.userCode = `\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${width}.0, ${height}.0);\n vec4 values = ${glsl.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${glsl.output} = result;\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\nimport {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {TextureUsage} from '../tex_util';\n\nimport {FromPixelsProgram} from './FromPixels_utils/from_pixels_gpu';\nimport {FromPixelsPackedProgram} from './FromPixels_utils/from_pixels_packed_gpu';\n\nexport const fromPixelsConfig: KernelConfig = {\n kernelName: FromPixels,\n backendName: 'webgl',\n kernelFunc: fromPixels as unknown as KernelFunc,\n};\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\nlet willReadFrequently = env().getBool('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU');\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 const newWillReadFrequently =\n env().getBool('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU');\n if (fromPixels2DContext == null ||\n newWillReadFrequently !== willReadFrequently) {\n willReadFrequently = newWillReadFrequently;\n fromPixels2DContext =\n document.createElement('canvas').getContext(\n '2d', {willReadFrequently});\n }\n\n fromPixels2DContext.canvas.width = width;\n fromPixels2DContext.canvas.height = height;\n fromPixels2DContext.drawImage(\n pixels as HTMLVideoElement | HTMLImageElement | ImageBitmap, 0, 0,\n width, height);\n pixels = fromPixels2DContext.canvas;\n }\n\n const tempPixelHandle = backend.makeTensorInfo(texShape, 'int32');\n // This is a byte texture with pixels.\n backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;\n backend.gpgpu.uploadPixelDataToTexture(\n backend.getTexture(tempPixelHandle.dataId), pixels as ImageData);\n const program = env().getBool('WEBGL_PACK') ?\n new FromPixelsPackedProgram(outShape) :\n new FromPixelsProgram(outShape);\n const res = backend.runWebGLProgram(program, [tempPixelHandle], 'int32');\n backend.disposeData(tempPixelHandle.dataId);\n return res;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DProgram} from '../conv_gpu';\nimport {Conv2DPackedProgram} from '../conv_packed_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 const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n\n const prepareInputs = (): TensorInfo[] => {\n const inputs: TensorInfo[] = [x, filter];\n\n // If the input is a 1-D tensor, align it with the channels.\n //\n // For fusedConv2d, the inputs (x, W, bias, preluActivationWeights) are\n // supposed to be aligned with the dataFormat. The 4-D tensor inputs or\n // scalar inputs are originally aligned, but the 1-D tensor inputs are\n // supposed to be aligned with the channels (only bias and PReLU activation\n // weights could be a 1-D tensor).\n const alignInputWithDataFormat =\n (input: TensorInfo, dataFormat: 'NHWC'|'NCHW'): TensorInfo => {\n if (dataFormat === 'NCHW' && input.shape.length === 1 &&\n input.shape[0] !== 1) {\n const alignedInput = reshape({\n inputs: {x: input},\n backend,\n attrs: {shape: [input.shape[0], 1, 1]}\n });\n intermediates.push(alignedInput);\n return alignedInput;\n }\n return input;\n };\n\n if (hasBias) {\n inputs.push(alignInputWithDataFormat(bias, dataFormat));\n }\n\n if (hasPreluActivationWeights) {\n inputs.push(alignInputWithDataFormat(preluActivationWeights, dataFormat));\n }\n\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as unknown as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n return inputs;\n };\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 (convInfo.strideWidth <= 2 && $dataFormat === 'channelsLast'\n && env().getBool('WEBGL_EXP_CONV')\n ) {\n const fusedActivation =\n activation ? mapActivationToShaderProgram(activation, true) : null;\n const program = new Conv2DPackedProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n const customValues = [\n [convInfo.padInfo.top, convInfo.padInfo.left],\n [convInfo.strideHeight, convInfo.strideWidth],\n [convInfo.dilationHeight, convInfo.dilationWidth],\n [convInfo.inHeight, convInfo.inWidth]\n ];\n const inputs = prepareInputs();\n out = backend.runWebGLProgram(program, inputs, 'float32', customValues);\n } else if (env().getBool('WEBGL_CONV_IM2COL')) {\n out = conv2dWithIm2Row({\n x,\n filter,\n convInfo,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n } else {\n const fusedActivation =\n activation ? mapActivationToShaderProgram(activation, false) : null;\n const program = new Conv2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n\n const inputs = prepareInputs();\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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as 'float32',\n '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 const customValues = [\n [convInfo.padInfo.top, convInfo.padInfo.left],\n [convInfo.strideHeight, convInfo.strideWidth],\n [convInfo.dilationHeight, convInfo.dilationWidth],\n [convInfo.inHeight, convInfo.inWidth]\n ];\n const result =\n backend.runWebGLProgram(program, programInputs, 'float32', customValues);\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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class GatherNDProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n constructor(\n private sliceDim: number, private strides: number[], shape: number[],\n private paramsShape: number[]) {\n this.outputShape = shape;\n const dtype = getCoordsDataType(shape.length);\n\n let mainLoop = `\n int index;`;\n for (let j = 0; j < this.sliceDim; j++) {\n mainLoop += `\n index = round(getIndices(coords[0], ${j}));\n out_of_bounds = out_of_bounds || index < 0;\n out_of_bounds = out_of_bounds || index >= ${this.paramsShape[j]};\n flattenIndex += index * ${this.strides[j]};`;\n }\n\n this.userCode = `\n void main() {\n ${dtype} coords = getOutputCoords();\n int flattenIndex = 0;\n bool out_of_bounds = false;\n\n ${mainLoop}\n\n setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherNd, GatherNdInputs, KernelConfig, KernelFunc, Rank, 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 params.shape);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport type GatherShape = [number, number, number, number];\n\nexport class GatherProgram implements GPGPUProgram {\n variableNames = ['A', 'indices'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: GatherShape, outputShape: GatherShape) {\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 int index = int(getIndices(resRC.x, resRC.z));\n float inBounds = (index >= 0) && (index < ${aShape[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${sourceCoords}));\n }\n `;\n }\n}\n\n// The input and output are always flattened into rank 4 tensors.\nfunction getSourceCoords(aShape: GatherShape, 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('index');\n } else {\n sourceCoords.push(`${currentCoords[i]}`);\n }\n }\n return sourceCoords.join();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherV2, GatherV2Attrs, GatherV2Inputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util, env} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {GatherProgram, GatherShape} 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 if (env().get('DEBUG')) {\n // In debug mode, throw error when any index is out of bound.\n // Otherwise, just fill out of bounds with zeroes.\n const indicesVals = backend.readSync(indices.dataId) as TypedArray;\n const axisDim = x.shape[parsedAxis];\n for (let i = 0; i < indicesVals.length; ++i) {\n const index = indicesVals[i];\n util.assert(\n index <= axisDim - 1 && index >= 0,\n () =>\n `GatherV2: the index value ${index} is not in [0, ${axisDim - 1}]`);\n }\n }\n\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 as GatherShape,\n flattenOutputShape as GatherShape);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Log} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {logImplCPU} from '../kernel_utils/shared';\n\n// Windows chrome return 0 if the input is negative value. We will specifically\n// return NaN if the input is 0 to solve compatiblity issue.\nconst LOG = CHECK_NAN_SNIPPET_UNARY + `\n return x < 0.0 ? 0./0. : log(x);\n`;\n\nconst LOG_PACKED = `\n vec4 result = log(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\n result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\n result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\n result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Log1p} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOG1P = CHECK_NAN_SNIPPET_UNARY + `\n return log(1.0 + x);\n`;\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n xShape: number[], radius: number, bias: number, alpha: number,\n beta: number) {\n const rad = radius;\n const maxD = xShape[3] - 1;\n this.outputShape = xShape;\n\n // optimize pow(bias + alpha * sum, -beta)\n // src: https://github.com/tensorflow/tensorflow/..\n // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..\n // tensorflow/core/kernels/mkl_lrn_op.cc#L320\n let powOperator;\n const basis = `float(${bias}) + float(${alpha}) * sum`;\n if (beta === 0.5) {\n powOperator = `inversesqrt(${basis})`;\n } else if (beta === 1.0) {\n powOperator = `1.0/(${basis})`;\n } else {\n powOperator = `exp(log(${basis}) * float(-${beta}));`;\n }\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${rad}; j <= ${rad}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${maxD}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${powOperator};\n setOutput(val);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n xShape: number[], radius: number, bias: number, alpha: number,\n beta: number) {\n const rad = radius;\n const maxD = xShape[3] - 1;\n this.outputShape = xShape;\n\n // optimize pow(bias + alpha * sum, -beta)\n // src: https://github.com/tensorflow/tensorflow/..\n // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..\n // tensorflow/core/kernels/mkl_lrn_op.cc#L320\n let powOperator;\n const basis = `float(${bias}) + float(${alpha}) * sum`;\n if (beta === 0.5) {\n powOperator = `inversesqrt(${basis})`;\n } else if (beta === 1.0) {\n powOperator = `1.0/(${basis})`;\n } else {\n powOperator = `exp(log(${basis}) * float(-${beta}));`;\n }\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${rad};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${rad}; j <= ${rad}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${maxD}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${powOperator};\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, LRN, LRNAttrs, LRNInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {LRNProgram} from '../lrn_gpu';\nimport {LRNPackedProgram} from '../lrn_packed_gpu';\n\nexport const lrn =\n (args: {inputs: LRNInputs, backend: MathBackendWebGL, attrs: LRNAttrs}):\n TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n const program = env().getBool('WEBGL_PACK_NORMALIZATION') ?\n new LRNPackedProgram(x.shape, depthRadius, bias, alpha, beta) :\n new LRNProgram(x.shape, depthRadius, bias, alpha, beta);\n return backend.runWebGLProgram(program, [x], x.dtype);\n };\n\n// tslint:disable-next-line: variable-name\nexport const LRNConfig: KernelConfig = {\n kernelName: LRN,\n backendName: 'webgl',\n kernelFunc: lrn as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNGradProgram implements GPGPUProgram {\n variableNames = ['inputImage', 'outputImage', 'dy'];\n outputShape: number[] = [];\n userCode: string;\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n depth: number;\n\n constructor(\n inputShape: number[], depthRadius: number, bias: number, alpha: number,\n beta: number) {\n this.outputShape = inputShape;\n this.depth = inputShape[3];\n this.depthRadius = depthRadius;\n this.bias = bias;\n this.alpha = alpha;\n this.beta = beta;\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${depthRadius})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${depthRadius} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${alpha}) * norm + float(${bias});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${alpha})\n * float(${beta})\n * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${beta});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LRNGrad, LRNGradAttrs, LRNGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {LRNGradProgram} from '../lrn_grad_gpu';\n\nexport const lrnGrad = (args: {\n inputs: LRNGradInputs,\n backend: MathBackendWebGL,\n attrs: LRNGradAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x, y, dy} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n const program = new LRNGradProgram(x.shape, depthRadius, bias, alpha, beta);\n return backend.runWebGLProgram(program, [x, y, dy], x.dtype);\n};\n\n// tslint:disable-next-line: variable-name\nexport const LRNGradConfig: KernelConfig = {\n kernelName: LRNGrad,\n backendName: 'webgl',\n kernelFunc: lrnGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelFunc, Max, MaxAttrs, MaxInputs, TensorInfo} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 {KernelConfig, KernelFunc, Maximum} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {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 bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MaxPool2DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy', 'maxPos'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const lastIndex = effectiveFilterHeight * effectiveFilterWidth - 1;\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${lastIndex} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${effectiveFilterWidth} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class MaxPool3DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy', 'maxPos'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const lastIndex =\n effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1;\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${lastIndex} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +\n wR * ${effectiveFilterWidth} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool3DGrad, MaxPool3DGradAttrs, MaxPool3DGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MaxPool3DBackpropProgram} from '../max_pool_backprop_gpu';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function maxPool3DGrad(args: {\n inputs: MaxPool3DGradInputs,\n backend: MathBackendWebGL,\n attrs: MaxPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n\n const maxPool3dPositionsProgram =\n new Pool3DProgram(convInfo, 'max', true /* get positions */);\n const maxPool3dPositions =\n backend.runWebGLProgram(maxPool3dPositionsProgram, [x], x.dtype);\n const maxPoolBackpropProgram = new MaxPool3DBackpropProgram(convInfo);\n const result = backend.runWebGLProgram(\n maxPoolBackpropProgram, [dy, maxPool3dPositions], x.dtype);\n backend.disposeIntermediateTensorInfo(maxPool3dPositions);\n return result;\n}\n\nexport const maxPool3DGradConfig: KernelConfig = {\n kernelName: MaxPool3DGrad,\n backendName: 'webgl',\n kernelFunc: maxPool3DGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 unknown 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 unknown 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 {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from '../kernels/Reshape';\n\nexport function meanImpl(\n x: TensorInfo, reduceShape: number[], outShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput =\n reshape({inputs: {x}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const reduced = reduce(reshapedInput, 'float32', 'mean', backend);\n const reshapedOutput =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n\n return reshapedOutput;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Minimum} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {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 bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class MirrorPadProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric') {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const unpackedCoords =\n ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);\n const offset = mode === 'reflect' ? 0 : 1;\n\n if (rank === 1) {\n this.userCode = `\n int start = ${start};\n int end = ${end};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${offset};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${offset};\n }\n setOutput(getX(outC - start));\n }\n `;\n return;\n }\n this.userCode = `\n ${dtype} start = ${dtype}(${start});\n ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outC = getOutputCoords();\n for (int i = 0; i < ${rank}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${offset};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${offset};\n }\n }\n ${dtype} coords = outC - start;\n setOutput(getX(${unpackedCoords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\n/**\n * Example shader code for\n * `mirrorPad(tf.tensor1d([1, 2, 3], 'int32'), [[2, 2]], 'reflect')`\n * ```\n * const int start = int(2);\n * const int end = int(5);\n *\n * void main() {\n * int outputLoc = getOutputCoords();\n * vec4 result = vec4(0.);\n *\n * int rc = outputLoc;\n *\n * int source = rc;\n * if (source < start) {\n * source = start * 2 - source - 0;\n * } else if (source >= end) {\n * source = (end - 1) * 2 - source + 0;\n * }\n * source -= start;\n *\n * result[0] = getChannel(getX(source), source);\n * rc += 1;\n * if(rc < 6) {\n * int source = rc;\n * if (source < start) {\n * source = start * 2 - source - 0;\n * } else if (source >= end) {\n * source = (end - 1) * 2 - source + 0;\n * }\n * source -= start;\n *\n * result[1] = getChannel(getX(source), source);\n * }\n *\n * setOutput(result);\n * }\n * ```\n */\nexport class MirrorPadPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric') {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const coords = getChannels('rc', rank);\n const source = getChannels('source', rank);\n const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;\n const innerDims =\n rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;\n const offset = mode === 'reflect' ? 0 : 1;\n\n let mainLoop = '';\n if (rank === 1) {\n const padSetup = `\n ${dtype} source = rc;\n if (source < start) {\n source = start * 2 - source - ${offset};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${offset};\n }\n source -= start;\n `;\n mainLoop = `\n ${dtype} rc = outputLoc;\n ${padSetup}\n result[0] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[1] = getChannel(getX(${source.join()}), ${innerDims});\n }\n `;\n } else {\n const padSetup = `\n ${dtype} source = rc;\n ${dtype} lt = ${dtype}(lessThan(source, start));\n ${dtype} gte = ${dtype}(greaterThanEqual(source, end));\n ${dtype} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${offset}) +\n gte * ((end - 1) * 2 - source + ${offset});\n source -= start;\n `;\n\n mainLoop = `\n ${dtype} rc = outputLoc;\n ${padSetup}\n result[0] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[1] = getChannel(getX(${source.join()}), ${innerDims});\n }\n rc = outputLoc;\n ${coords[rank - 2]} += 1;\n if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {\n ${padSetup}\n result[2] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[3] = getChannel(getX(${source.join()}), ${innerDims});\n }\n }\n `;\n }\n\n this.userCode = `\n const ${dtype} start = ${dtype}(${start});\n const ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${mainLoop}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, MirrorPad, MirrorPadAttrs, MirrorPadInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MirrorPadProgram} from '../mirror_pad_gpu';\nimport {MirrorPadPackedProgram} from '../mirror_pad_packed_gpu';\n\nexport const mirrorPadKernelFunc: (params: {\n inputs: MirrorPadInputs,\n backend: MathBackendWebGL,\n attrs: MirrorPadAttrs\n}) => TensorInfo = ({inputs, backend, attrs}) => {\n const {x} = inputs;\n const {paddings, mode} = attrs;\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new MirrorPadPackedProgram(x.shape, paddings, mode) :\n new MirrorPadProgram(x.shape, paddings, mode);\n\n const output = backend.runWebGLProgram(program, [x], x.dtype);\n\n return output;\n};\n\nexport const mirrorPadConfig: KernelConfig = {\n kernelName: MirrorPad,\n backendName: 'webgl',\n kernelFunc: mirrorPadKernelFunc as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Mod} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_PACKED} 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 bvec4 isNaN = equal(b, vec4(0.0));\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class MultinomialProgram implements GPGPUProgram {\n variableNames = ['probs'];\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'seed', type: 'float' as UniformType}];\n\n constructor(batchSize: number, numOutcomes: number, numSamples: number) {\n this.outputShape = [batchSize, numSamples];\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${numOutcomes - 1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${numOutcomes - 1}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {RealDiv} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// Without the equality check div produces 0.9999 for a = b, which when\n// floored can cause errors.\nconst DIV = `\nif (a == b) {\n return 1.0;\n};\nreturn a / b;`;\n\n// We do the same as in ./binaryop_gpu, with vec4 and ivec4.\n// On Linux, the vectorized implementation produces NaNs when a and b are 0.\nconst DIV_PACKED = `\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n`;\n\nexport const realDiv = binaryKernelFunc(\n {opSnippet: DIV, packedOpSnippet: DIV_PACKED, checkOutOfBounds: true});\n\nexport const realDivConfig: KernelConfig = {\n kernelName: RealDiv,\n backendName: 'webgl',\n kernelFunc: realDiv,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sub} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {subImplCPU as cpuSub} from '../kernel_utils/shared';\n\nconst SUB = 'return a - b;';\n\nexport const sub = binaryKernelFunc({\n opSnippet: SUB,\n packedOpSnippet: SUB,\n supportsComplex: true,\n cpuKernelImpl: cpuSub\n});\n\nexport const subConfig: KernelConfig = {\n kernelName: Sub,\n backendName: 'webgl',\n kernelFunc: sub\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Softmax, SoftmaxAttrs, SoftmaxInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {exp} from './Exp';\nimport {max} from './Max';\nimport {realDiv} from './RealDiv';\nimport {reshape} from './Reshape';\nimport {sub} from './Sub';\nimport {sum} from './Sum';\n\nexport function softmax(args: {\n inputs: SoftmaxInputs,\n backend: MathBackendWebGL,\n attrs: SoftmaxAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {dim} = attrs;\n\n const axes = util.parseAxisParam([dim], logits.shape);\n\n const maxLogit = max({\n inputs: {x: logits},\n backend,\n attrs: {reductionIndices: axes, keepDims: false}\n });\n\n const expandedShape = backend_util.expandShapeToKeepDim(maxLogit.shape, axes);\n\n const maxLogitsReshaped =\n reshape({inputs: {x: maxLogit}, backend, attrs: {shape: expandedShape}});\n const a =\n sub({inputs: {a: logits, b: maxLogitsReshaped}, backend}) as TensorInfo;\n const b = exp({inputs: {x: a}, backend}) as TensorInfo;\n const sumExp =\n sum({inputs: {x: b}, backend, attrs: {axis: axes, keepDims: false}});\n const sumExpReshaped =\n reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}});\n\n const res =\n realDiv({inputs: {a: b, b: sumExpReshaped}, backend}) as TensorInfo;\n\n backend.disposeIntermediateTensorInfo(maxLogit);\n backend.disposeIntermediateTensorInfo(maxLogitsReshaped);\n backend.disposeIntermediateTensorInfo(a);\n backend.disposeIntermediateTensorInfo(b);\n backend.disposeIntermediateTensorInfo(sumExp);\n backend.disposeIntermediateTensorInfo(sumExpReshaped);\n\n return res;\n}\n\nexport const softmaxConfig: KernelConfig = {\n kernelName: Softmax,\n backendName: 'webgl',\n kernelFunc: softmax as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Neg, NegInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {negImplCPU} from '../kernel_utils/shared';\nimport {CHECK_NAN_SNIPPET, UnaryOpProgram} from '../unaryop_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nconst NEG = CHECK_NAN_SNIPPET + `\n return -x;\n`;\n\nconst NEG_PACKED = `\n vec4 result = -x;\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\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_PACKED);\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class OneHotProgram implements GPGPUProgram {\n variableNames = ['indices'];\n outputShape: number[];\n userCode: string;\n\n // Caching uniform location for speed.\n seedLoc: WebGLUniformLocation;\n\n constructor(\n numIndices: number, depth: number, onValue: number, offValue: number) {\n this.outputShape = [numIndices, depth];\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${offValue}), float(${onValue}),\n float(index == coords.y)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, OneHot, OneHotAttrs, OneHotInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {OneHotProgram} from '../onehot_gpu';\nimport {reshape} from './Reshape';\n\nexport const oneHot = (args: {\n inputs: OneHotInputs,\n backend: MathBackendWebGL,\n attrs: OneHotAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {indices} = inputs;\n const {dtype, 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], 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Pack, PackAttrs, PackInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class PadProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'value', type: 'float' as UniformType}];\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n constantValue: number) {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const type = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const unpackedCoords =\n ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);\n\n if (rank === 1) {\n this.userCode = `\n int start = ${start};\n int end = ${end};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `;\n return;\n }\n this.userCode = `\n ${type} start = ${type}(${start});\n ${type} end = ${type}(${end});\n\n void main() {\n ${type} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${type} coords = outC - start;\n setOutput(getX(${unpackedCoords}));\n }\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class PadPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'value', type: 'float' as UniformType}];\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n constantValue: number) {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const coords = getChannels('rc', rank);\n const source = getChannels('source', rank);\n const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;\n const innerDims =\n rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;\n\n const componentSetup = [\n `${dtype} rc = outputLoc;`, `${coords[rank - 1]} += 1;\n if(${cLimit}) {\n `,\n rank === 1 ? '' : `}\n rc = outputLoc;\n ${coords[rank - 2]} += 1;\n if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {`,\n rank === 1 ? '' : ` ${coords[rank - 1]} += 1;\n if(${cLimit}) {`\n ];\n\n const paddingArea = rank === 1 ?\n 'rc < start || rc >= end' :\n 'any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))';\n let mainLoop = '';\n for (let i = 0, j = rank === 1 ? 2 : 4; i < j; i++) {\n mainLoop += `\n ${componentSetup[i]}\n if (${paddingArea}) {\n result[${i}] = float(value);\n } else {\n ${dtype} source = rc - start;\n result[${i}] = getChannel(getX(${source.join()}), ${innerDims});\n }\n `;\n }\n mainLoop += (rank === 1 ? `} ` : `}}`);\n\n this.userCode = `\n const ${dtype} start = ${dtype}(${start});\n const ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${mainLoop}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, PadV2, PadV2Attrs, PadV2Inputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {PadProgram} from '../pad_gpu';\nimport {PadPackedProgram} from '../pad_packed_gpu';\nimport {fill} from './Fill';\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 if (util.sizeFromShape(x.shape) === 0) {\n // Short-circuit the computation, since x doesn't have value, only\n // the shape is used to compute output shape to pad.\n const outputShape = paddings.map(\n (p, i) =>\n p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n return fill({\n backend,\n attrs: {shape: outputShape, value: constantValue, dtype: x.dtype}\n });\n }\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Pow} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_PACKED} 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 bvec4 isNaN1 = lessThan(a, vec4(0.0));\n bvec4 isNaN2 = lessThan(floor(b), b);\n bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, RaggedGather, RaggedGatherAttrs, RaggedGatherInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {raggedGatherImplCPU} from '../kernel_utils/shared';\n\nexport function raggedGather(args: {\n inputs: RaggedGatherInputs,\n backend: MathBackendWebGL,\n attrs: RaggedGatherAttrs\n}): TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {paramsNestedSplits, paramsDenseValues, indices} = inputs;\n const {outputRaggedRank} = attrs;\n\n const $paramsNestedSplits =\n paramsNestedSplits.map(t => backend.readSync(t.dataId) as TypedArray);\n const $paramsNestedSplitsShapes = paramsNestedSplits.map(t => t.shape);\n const $paramsDenseValues =\n backend.readSync(paramsDenseValues.dataId) as TypedArray;\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n\n const [outputNestedSplits, outputDenseValues, outputDenseValuesShape] =\n raggedGatherImplCPU(\n $paramsNestedSplits, $paramsNestedSplitsShapes, $paramsDenseValues,\n paramsDenseValues.shape, paramsDenseValues.dtype, $indices,\n indices.shape, outputRaggedRank);\n\n const outputNestedSplitsTensors = outputNestedSplits.map(\n (splits) => backend.makeTensorInfo([splits.length], 'int32', splits));\n\n const outputDenseValuesTensor = backend.makeTensorInfo(\n outputDenseValuesShape, paramsDenseValues.dtype, outputDenseValues);\n\n return outputNestedSplitsTensors.concat([outputDenseValuesTensor]);\n}\n\nexport const raggedGatherConfig: KernelConfig = {\n kernelName: RaggedGather,\n backendName: 'webgl',\n kernelFunc: raggedGather as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, RaggedRange, RaggedRangeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {raggedRangeImplCPU} from '../kernel_utils/shared';\n\nexport function raggedRange(\n args: {inputs: RaggedRangeInputs, backend: MathBackendWebGL}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {starts, limits, deltas} = inputs;\n\n const $starts = backend.readSync(starts.dataId) as TypedArray;\n const $limits = backend.readSync(limits.dataId) as TypedArray;\n const $deltas = backend.readSync(deltas.dataId) as TypedArray;\n\n const [rtNestedSplitsData, rtDenseValuesData] = raggedRangeImplCPU(\n $starts, starts.shape, starts.dtype, $limits, limits.shape, $deltas,\n deltas.shape);\n\n const rtNestedSplits = backend.makeTensorInfo(\n [rtNestedSplitsData.length], 'int32', rtNestedSplitsData);\n const rtDenseValues = backend.makeTensorInfo(\n [rtDenseValuesData.length], starts.dtype, rtDenseValuesData);\n\n return [rtNestedSplits, rtDenseValues];\n}\n\nexport const raggedRangeConfig: KernelConfig = {\n kernelName: RaggedRange,\n backendName: 'webgl',\n kernelFunc: raggedRange as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, RaggedTensorToTensor, RaggedTensorToTensorAttrs, RaggedTensorToTensorInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {raggedTensorToTensorImplCPU} from '../kernel_utils/shared';\n\nexport function raggedTensorToTensor(args: {\n inputs: RaggedTensorToTensorInputs,\n backend: MathBackendWebGL,\n attrs: RaggedTensorToTensorAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {shape, values, defaultValue, rowPartitionTensors} = inputs;\n const {rowPartitionTypes} = attrs;\n\n const $shape = backend.readSync(shape.dataId) as TypedArray;\n const $values = backend.readSync(values.dataId) as TypedArray;\n const $defaultValue = backend.readSync(defaultValue.dataId) as TypedArray;\n const $rowPartitionValues =\n rowPartitionTensors.map(t => backend.readSync(t.dataId) as TypedArray);\n const rowPartitionValuesShapes = rowPartitionTensors.map(t => t.shape);\n\n const [outputShape, output] = raggedTensorToTensorImplCPU(\n $shape, shape.shape, $values, values.shape, values.dtype, $defaultValue,\n defaultValue.shape, $rowPartitionValues, rowPartitionValuesShapes,\n rowPartitionTypes);\n return backend.makeTensorInfo(outputShape, values.dtype, output);\n}\n\nexport const raggedTensorToTensorConfig: KernelConfig = {\n kernelName: RaggedTensorToTensor,\n backendName: 'webgl',\n kernelFunc: raggedTensorToTensor as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Range, RangeAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Reciprocal} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst RECIPROCAL = `return 1.0 / x;`;\n\nexport const reciprocal = unaryKernelFunc({opSnippet: RECIPROCAL});\n\nexport const reciprocalConfig: KernelConfig = {\n kernelName: Reciprocal,\n backendName: 'webgl',\n kernelFunc: reciprocal,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Relu} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst RELU = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : x;\n`;\n\nconst RELU_PACKED = `\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const relu =\n unaryKernelFunc({opSnippet: RELU, packedOpSnippet: RELU_PACKED});\n\nexport const reluConfig: KernelConfig = {\n kernelName: Relu,\n backendName: 'webgl',\n kernelFunc: relu as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC =\n `(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` +\n ` - vec2(0.5)`;\n } else {\n sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC = `(vec3(yRC) + vec3(0.5)) * ` +\n `effectiveInputOverOutputRatioRC - vec3(0.5)`;\n } else {\n sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,\n ${oldWidth}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${depth - 1};\n bool hasNextRow = coords.z < ${newWidth - 1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeBilinearProgram} from '../resize_bilinear_gpu';\nimport {ResizeBilinearPackedProgram} from '../resize_bilinear_packed_gpu';\n\nexport function resizeBilinear(args: {\n inputs: ResizeBilinearInputs,\n backend: MathBackendWebGL,\n attrs: ResizeBilinearAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n const [newHeight, newWidth] = size;\n\n const program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?\n new ResizeBilinearPackedProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters) :\n new ResizeBilinearProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters);\n return backend.runWebGLProgram(program, [images], 'float32');\n}\n\nexport const resizeBilinearConfig: KernelConfig = {\n kernelName: ResizeBilinear,\n backendName: 'webgl',\n kernelFunc: resizeBilinear as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n dyShape: [number, number, number, number],\n inputShape: [number, number, number, number], alignCorners: boolean) {\n this.outputShape = inputShape;\n const [, xHeight, xWidth, ] = inputShape;\n const [, yHeight, yWidth] = dyShape;\n\n // In the backwards pass, we want to find the pixels that were generated for\n // each pixel in the input image the forward pass and add the corresponding\n // coefficient from dy to the gradient (with some interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${heightScale});\n const float widthScale = float(${widthScale});\n\n const float invHeightScale = float(${invHeightScale});\n const float invWidthScale = float(${invWidthScale});\n\n const int winHeight = int(${winHeight});\n const int winWidth = int(${winWidth});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${yHeight}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${yWidth}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${xHeight - 1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${xWidth - 1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeBilinearGrad, ResizeBilinearGradAttrs, ResizeBilinearGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeBilinearBackpropProgram} from '../resize_bilinear_backprop_gpu';\n\nexport function resizeBilinearGrad(args: {\n inputs: ResizeBilinearGradInputs,\n backend: MathBackendWebGL,\n attrs: ResizeBilinearGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n const program = new ResizeBilinearBackpropProgram(\n dy.shape as [number, number, number, number],\n images.shape as [number, number, number, number], alignCorners);\n\n return backend.runWebGLProgram(program, [dy], dy.dtype);\n}\n\nexport const resizeBilinearGradConfig: KernelConfig = {\n kernelName: ResizeBilinearGrad,\n backendName: 'webgl',\n kernelFunc: resizeBilinearGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeighborProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n // When align corners is false, we rounds the value with floor.\n const roundBase = alignCorners ? '0.5' : '0.0';\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC =\n `max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` +\n `, vec2(0.0))`;\n } else {\n sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;\n }\n this.userCode = `\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeighborPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n // When align corners is false, we rounds the value with floor.\n const roundBase = alignCorners ? '0.5' : '0.0';\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC = `max((vec3(yRC) + vec3(0.5)) * ` +\n `effectiveInputOverOutputRatioRC, vec3(0.0))`;\n } else {\n sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,\n ${oldWidth}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${depth - 1};\n bool hasNextRow = coords.z < ${newWidth - 1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeNearestNeighborProgram} from '../resize_nearest_neighbor_gpu';\nimport {ResizeNearestNeighborPackedProgram} from '../resize_nearest_neighbor_packed_gpu';\n\nexport function resizeNearestNeighbor(args: {\n inputs: ResizeNearestNeighborInputs,\n backend: MathBackendWebGL,\n attrs: ResizeNearestNeighborAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n const [newHeight, newWidth] = size;\n\n const program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?\n new ResizeNearestNeighborPackedProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters) :\n new ResizeNearestNeighborProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters);\n return backend.runWebGLProgram(program, [images], images.dtype);\n}\n\nexport const resizeNearestNeighborConfig: KernelConfig = {\n kernelName: ResizeNearestNeighbor,\n backendName: 'webgl',\n kernelFunc: resizeNearestNeighbor as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeigborBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n dyShape: [number, number, number, number],\n inputShape: [number, number, number, number], alignCorners: boolean) {\n this.outputShape = inputShape;\n const [, xHeight, xWidth, ] = inputShape;\n const [, yHeight, yWidth] = dyShape;\n\n // In the backwards pass, we want to find the pixels that were generated for\n // each pixel in the input image the forward pass and add the corresponding\n // coefficient from dy to the gradient (with some interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${heightScale});\n const float widthScale = float(${widthScale});\n\n const float invHeightScale = float(${invHeightScale});\n const float invWidthScale = float(${invWidthScale});\n\n const int winHeight = int(${winHeight});\n const int winWidth = int(${winWidth});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${yHeight}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${yWidth}) {\n continue;\n }\n\n float sourceFracRow =\n float(${effectiveXSize[0]}) *\n (float(dyR) / float(${effectiveYSize[0]}));\n\n float sourceFracCol =\n float(${effectiveXSize[1]}) *\n (float(dyC) / float(${effectiveYSize[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${xHeight}) - 1),\n ${alignCorners} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${xWidth}) - 1),\n ${alignCorners} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeNearestNeighborGrad, ResizeNearestNeighborGradAttrs, ResizeNearestNeighborGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeNearestNeigborBackpropProgram} from '../resize_nearest_neighbor_backprop_gpu';\n\nexport function resizeNearestNeighborGrad(args: {\n inputs: ResizeNearestNeighborGradInputs,\n backend: MathBackendWebGL,\n attrs: ResizeNearestNeighborGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n const program = new ResizeNearestNeigborBackpropProgram(\n dy.shape as [number, number, number, number],\n images.shape as [number, number, number, number], alignCorners);\n return backend.runWebGLProgram(program, [dy], dy.dtype);\n}\n\nexport const resizeNearestNeighborGradConfig: KernelConfig = {\n kernelName: ResizeNearestNeighborGrad,\n backendName: 'webgl',\n kernelFunc: resizeNearestNeighborGrad as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ReverseProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(xShape: number[], axis: number[]) {\n const rank = xShape.length;\n if (rank > 4) {\n throw new Error(\n `WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);\n }\n this.outputShape = xShape;\n\n if (rank === 1) {\n this.userCode = `\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${xShape[0]} - coord - 1));\n }\n `;\n return;\n }\n const getInCoord = (i: number) => {\n if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {\n return `${xShape[i]} - coords[${i}] - 1`;\n }\n return `coords[${i}]`;\n };\n const inCoords = xShape.map((_, i) => getInCoord(i)).join(',');\n const type = getCoordsDataType(rank);\n\n this.userCode = `\n void main() {\n ${type} coords = getOutputCoords();\n setOutput(getX(${inCoords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ReversePackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(xShape: number[], axis: number[]) {\n const rank = xShape.length;\n if (rank > 4) {\n throw new Error(\n `WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);\n }\n this.outputShape = xShape;\n const channels = getChannels('rc', rank);\n const nextColumn =\n `${channels[rank - 1]} + 1 < ${this.outputShape[rank - 1]}`;\n const nextRow = `${channels[rank - 2]} + 1 < ${this.outputShape[rank - 2]}`;\n const type = getCoordsDataType(rank);\n if (rank === 1) {\n this.userCode = `\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${xShape[0]} - rc - 1),\n ${xShape[0]} - rc - 1);\n if(${nextColumn}){\n result.g = getChannel(getX(${xShape[0]} - (rc + 1) - 1),\n ${xShape[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `;\n } else {\n this.userCode = `\n void main() {\n ${type} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${getR(channels.slice())};\n if(${nextColumn}){\n result.g = ${getG(channels.slice())};\n }\n if(${nextRow}) {\n result.b = ${getB(channels.slice())};\n if(${nextColumn}) {\n result.a = ${getA(channels.slice())};\n }\n }\n setOutput(result);\n }\n `;\n }\n\n function getR(channels: string[]): string {\n return getChannel(channels);\n }\n\n function getG(channels: string[]): string {\n channels[rank - 1] = '(' + channels[rank - 1] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getB(channels: string[]): string {\n channels[rank - 2] = '(' + channels[rank - 2] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getA(channels: string[]): string {\n channels[rank - 1] = '(' + channels[rank - 1] + ` + 1)`;\n channels[rank - 2] = '(' + channels[rank - 2] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getChannel(channels: string[]): string {\n const inCoordsArray = xShape.map((_, i) => getInCoord(i, channels));\n const inCoords = inCoordsArray.join(',');\n const innerDims = inCoordsArray.slice(-2).join(',');\n return `getChannel(getX(${inCoords}), vec2(${innerDims}))`;\n }\n\n function getInCoord(i: number, channels1: string[]): string {\n if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {\n return `${xShape[i]} - ${channels1[i]} - 1`;\n } else {\n return `${channels1[i]}`;\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Reverse, ReverseAttrs, ReverseInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ReverseProgram} from '../reverse_gpu';\nimport {ReversePackedProgram} from '../reverse_packed_gpu';\n\nimport {identity} from './Identity';\n\nexport function reverse(args: {\n inputs: ReverseInputs,\n backend: MathBackendWebGL,\n attrs: ReverseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dims} = attrs;\n\n const xRank = x.shape.length;\n\n const $dims = util.parseAxisParam(dims, x.shape);\n if (xRank === 0) {\n return identity({inputs: {x}, backend});\n }\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new ReversePackedProgram(x.shape, $dims) :\n new ReverseProgram(x.shape, $dims);\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const reverseConfig: KernelConfig = {\n kernelName: Reverse,\n backendName: 'webgl',\n kernelFunc: reverse as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class RotateProgram implements GPGPUProgram {\n variableNames = ['Image'];\n outputShape: number[] = [];\n userCode: string;\n customUniforms = [{name: 'params', type: 'vec4' as UniformType}];\n constructor(\n imageShape: [number, number, number, number],\n fillValue: number|[number, number, number]) {\n const imageHeight = imageShape[1];\n const imageWidth = imageShape[2];\n this.outputShape = imageShape;\n\n let fillSnippet = '';\n if (typeof fillValue === 'number') {\n fillSnippet = `float outputValue = ${fillValue.toFixed(2)};`;\n } else {\n fillSnippet = `\n vec3 fill = vec3(${fillValue.join(',')});\n float outputValue = fill[coords[3]];`;\n }\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${fillSnippet}\n if(coordX >= 0 && coordX < ${imageWidth} && coordY >= 0 && coordY < ${\n imageHeight}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, Tensor4D} from '@tensorflow/tfjs-core';\nimport {RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {RotateProgram} from '../rotate_gpu';\n\nexport const rotateWithOffsetConfig: KernelConfig = {\n kernelName: RotateWithOffset,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as RotateWithOffsetInputs;\n const {radians, fillValue, center} =\n attrs as unknown 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ScatterProgram implements GPGPUProgram {\n variableNames = ['updates', 'indices', 'defaultValue'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n updateSize: number, sliceDim: number, indicesRank: number,\n updatesRank: number, strides: number[], shape: number[],\n summingDupeIndex = true, defaultIsTensor = false) {\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 let defaultValuesString = '';\n if (defaultIsTensor) {\n defaultValuesString = 'coords[0], coords[1]';\n }\n const defaultValueSnippet = `getDefaultValue(${defaultValuesString})`;\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(${defaultValueSnippet}, sum, float(found)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ScatterPackedProgram implements GPGPUProgram {\n variableNames = ['updates', 'indices', 'defaultValue'];\n outputShape: number[];\n packedInputs = true;\n packedOutput = true;\n userCode: string;\n\n constructor(\n updateSize: number, sliceDim: number, indicesRank: number,\n updatesRank: number, strides: number[], shape: number[],\n summingDupeIndex = true, defaultIsTensor = false) {\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 let defaultValuesString = '';\n if (defaultIsTensor) {\n defaultValuesString = 'coords[0], coords[1]';\n }\n const defaultValueSnippet = `getDefaultValue(${defaultValuesString})`;\n\n const strideString = sliceDim > 1 ? 'strides[j]' : 'strides';\n const strideString2 = sliceDim > 1 ? 'strides[j + 1]' : 'strides';\n\n this.userCode = `\n ${stridesType} strides = ${stridesType}(${strides});\n\n void main() {\n ${dtype} coords = getOutputCoords();\n vec4 sum = vec4(0.);\n vec4 found = vec4(0.);\n for (int i = 0; i < ${updateSize}; i+=2) {\n ivec2 flattenedIndex = ivec2(0);\n for (int j = 0; j < ${sliceDim}; j+=2) {\n ivec4 index = round(${indicesSnippet});\n flattenedIndex += index.xz * ${strideString};\n if (j + 1 < ${sliceDim}) {\n flattenedIndex += index.yw * ${strideString2};\n }\n }\n if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||\n flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {\n vec4 updVals = ${updatesSnippet};\n if (flattenedIndex[0] == coords[0]) {\n sum.xy += updVals.xy;\n found.xy = vec2(1.);\n } else if (flattenedIndex[0] == coords[0] + 1) {\n sum.zw += updVals.xy;\n found.zw = vec2(1.);\n }\n if (flattenedIndex[1] == coords[0]) {\n sum.xy += updVals.zw;\n found.xy = vec2(1.);\n } else if (flattenedIndex[1] == coords[0] + 1) {\n sum.zw += updVals.zw;\n found.zw = vec2(1.);\n }\n }\n }\n setOutput(mix(${defaultValueSnippet}, sum, found));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, KernelConfig, KernelFunc, ScatterNd, ScatterNdAttrs, ScatterNdInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ScatterProgram} from '../scatter_gpu';\nimport {ScatterPackedProgram} from '../scatter_packed_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 let program;\n if (env().getBool('WEBGL_PACK')) {\n program = new ScatterPackedProgram(\n numUpdates, sliceRank, flattenIndices.shape.length,\n flattenX.shape.length, strides, flattenShape);\n } else {\n program = new ScatterProgram(\n numUpdates, sliceRank, flattenIndices.shape.length,\n flattenX.shape.length, strides, flattenShape);\n }\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class SearchSortedProgram implements GPGPUProgram {\n variableNames = ['sortedSequence', 'values'];\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'numInputs', type: 'int' as UniformType}];\n\n constructor(\n batchSize: number, numInputs: number, numValues: number,\n side: 'left'|'right') {\n this.outputShape = [batchSize, numValues];\n\n const webGL2LoopHead = 'while (left < right) {';\n // WebGL1 doesn't accept non constant loop conditions, so upper bound loop\n // iterations.\n const webGL1LoopHead = `for (int i = 0; i < ${\n Math.ceil(Math.log2(numInputs + 1))}; ++i) { if (left >= right) break;`;\n const loopHead = env().getNumber('WEBGL_VERSION') === 2 ? webGL2LoopHead :\n webGL1LoopHead;\n\n // left corresponds to lower bound and right to upper bound.\n const boundComparator = side === 'left' ? '<' : '<=';\n this.userCode = `\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${loopHead}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${boundComparator} value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int valueIndex = coords[1];\n\n float value = getValues(batch, valueIndex);\n\n setOutput(float(findBound(batch, value)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SearchSorted, SearchSortedAttrs, SearchSortedInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SearchSortedProgram} from '../search_sorted_gpu';\n\nexport function searchSorted(args: {\n inputs: SearchSortedInputs,\n backend: MathBackendWebGL,\n attrs: SearchSortedAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {sortedSequence, values} = inputs;\n const {side} = attrs;\n\n const program = new SearchSortedProgram(\n sortedSequence.shape[0], sortedSequence.shape[1], values.shape[1], side);\n const customValues = [[sortedSequence.shape[1]]];\n return backend.runWebGLProgram(\n program, [sortedSequence, values], 'int32', customValues);\n}\n\nexport const searchSortedConfig: KernelConfig = {\n kernelName: SearchSorted,\n backendName: 'webgl',\n kernelFunc: searchSorted as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class SelectProgram implements GPGPUProgram {\n variableNames = ['c', 'a', 'b'];\n outputShape: number[];\n userCode: string;\n\n constructor(cRank: number, shape: number[], rank: number) {\n this.outputShape = shape;\n\n let cCoords;\n let abCoords;\n if (rank > 4) {\n throw Error(`Where for rank ${rank} is not yet supported`);\n }\n\n if (rank === 1) {\n abCoords = `resRC`;\n cCoords = `resRC`;\n } else {\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];\n const cCoordVars = [];\n const abCoordVars = [];\n for (let i = 0; i < shape.length; i++) {\n abCoordVars.push(`${currentCoords[i]}`);\n if (i < cRank) {\n cCoordVars.push(`${currentCoords[i]}`);\n }\n }\n cCoords = cCoordVars.join();\n abCoords = abCoordVars.join();\n }\n\n const dtype = getCoordsDataType(rank);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n float cVal = getC(${cCoords});\n if (cVal >= 1.0) {\n setOutput(getA(${abCoords}));\n } else {\n setOutput(getB(${abCoords}));\n }\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Select, SelectInputs, TensorInfo, upcastType} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SelectProgram} from '../select_gpu';\n\nexport function select(args: {inputs: SelectInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {condition, t, e} = inputs;\n\n const program =\n new SelectProgram(condition.shape.length, t.shape, t.shape.length);\n return backend.runWebGLProgram(\n program, [condition, t, e], upcastType(t.dtype, e.dtype));\n}\n\nexport const selectConfig: KernelConfig = {\n kernelName: Select,\n backendName: 'webgl',\n kernelFunc: select as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, Selu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SELU = `\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${backend_util.SELU_SCALEALPHA};\n float scale = ${backend_util.SELU_SCALE};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`;\n\nexport const selu = unaryKernelFunc({opSnippet: SELU});\n\nexport const seluConfig: KernelConfig = {\n kernelName: Selu,\n backendName: 'webgl',\n kernelFunc: selu,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sigmoid} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {sigmoidImplCPU} from '../kernel_utils/shared';\n\nconst SIGMOID = CHECK_NAN_SNIPPET_UNARY + `\n return 1.0 / (1.0 + exp(-1.0 * x));\n`;\n\nconst SIGMOID_PACKED = `\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\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`;\nexport const sigmoid = unaryKernelFunc({\n opSnippet: SIGMOID,\n packedOpSnippet: SIGMOID_PACKED,\n cpuKernelImpl: sigmoidImplCPU\n});\n\nexport const sigmoidConfig: KernelConfig = {\n kernelName: Sigmoid,\n backendName: 'webgl',\n kernelFunc: sigmoid,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sign} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// Sign does not propagate NANs.\nconst SIGN = `\n if (isnan(x)) { return 0.0; }\n return sign(x);\n`;\n\nexport const sign = unaryKernelFunc({opSnippet: SIGN});\n\nexport const signConfig: KernelConfig = {\n kernelName: Sign,\n backendName: 'webgl',\n kernelFunc: sign,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sin} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\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\nconst SIN_PACKED = `\n vec4 result = sin(x);\n bvec4 isNaN = isnan(x);\n ${CHECK_NAN_SNIPPET_PACKED}\n return result;\n`;\n\nexport const sin =\n unaryKernelFunc({opSnippet: SIN, packedOpSnippet: SIN_PACKED});\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SparseFillEmptyRows, SparseFillEmptyRowsInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseFillEmptyRowsImplCPU} from '../kernel_utils/shared';\n\nexport function sparseFillEmptyRows(args: {\n inputs: SparseFillEmptyRowsInputs,\n backend: MathBackendWebGL\n}): [TensorInfo, TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {indices, values, denseShape, defaultValue} = inputs;\n if (denseShape.shape.length !== 1) {\n throw new Error(`Dense shape must be a vector, saw:\n ${denseShape.shape}`);\n }\n if (indices.shape.length !== 2) {\n throw new Error(`Indices must be a matrix, saw:\n ${indices.shape}`);\n }\n if (values.shape.length !== 1) {\n throw new Error(`Values must be a vector, saw:\n ${values.shape}`);\n }\n if (defaultValue.shape.length !== 0) {\n throw new Error(`Default value must be a scalar, saw:\n ${defaultValue.shape}`);\n }\n\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $values = backend.readSync(values.dataId) as TypedArray;\n const $denseShape = backend.readSync(denseShape.dataId) as TypedArray;\n const $defaultValue =\n backend.readSync(defaultValue.dataId)[0] as number;\n\n const [outputIndices, outputIndicesShape, outputValues,\n emptyRowIndicator, reverseIndexMap] =\n sparseFillEmptyRowsImplCPU(\n $indices, indices.shape, indices.dtype, $values, values.dtype,\n $denseShape, $defaultValue);\n return [\n backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),\n backend.makeTensorInfo(\n [outputIndicesShape[0]], values.dtype, outputValues),\n backend.makeTensorInfo(\n [emptyRowIndicator.length], 'bool',\n new Uint8Array(\n emptyRowIndicator.map((value: boolean) => Number(value)))),\n backend.makeTensorInfo(\n [reverseIndexMap.length], indices.dtype,\n new Int32Array(reverseIndexMap)),\n ];\n}\n\nexport const sparseFillEmptyRowsConfig: KernelConfig = {\n kernelName: SparseFillEmptyRows,\n backendName: 'webgl',\n kernelFunc: sparseFillEmptyRows as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SparseReshape, SparseReshapeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseReshapeImplCPU} from '../kernel_utils/shared';\n\nexport function sparseReshape(\n args: {inputs: SparseReshapeInputs, backend: MathBackendWebGL}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {inputIndices, inputShape, newShape} = inputs;\n if (inputIndices.shape.length !== 2) {\n throw new Error(`Input indices should be a matrix but received shape ${\n inputIndices.shape}`);\n }\n if (inputShape.shape.length !== 1) {\n throw new Error(`Input shape should be a vector but received shape ${\n inputShape.shape}`);\n }\n\n if (newShape.shape.length !== 1) {\n throw new Error(\n `Target shape should be a vector but received shape ${newShape.shape}`);\n }\n\n const $inputShape =\n Array.from(backend.readSync(inputShape.dataId) as TypedArray);\n const $inputIndices = backend.readSync(inputIndices.dataId) as TypedArray;\n const targetShape =\n Array.from(backend.readSync(newShape.dataId) as TypedArray);\n\n const [newIndices, indicesShape, outputShape] = sparseReshapeImplCPU(\n $inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape,\n targetShape);\n return [\n backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),\n backend.makeTensorInfo(\n [outputShape.length], newShape.dtype, new Int32Array(outputShape)),\n ];\n}\n\nexport const sparseReshapeConfig: KernelConfig = {\n kernelName: SparseReshape,\n backendName: 'webgl',\n kernelFunc: sparseReshape,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SparseSegmentMean, SparseSegmentMeanInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseSegmentReductionImplCPU} from '../kernel_utils/shared';\n\nexport function sparseSegmentMean(\n args: {inputs: SparseSegmentMeanInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.readSync(data.dataId) as TypedArray;\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $segmentIds = backend.readSync(segmentIds.dataId) as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImplCPU(\n $data, data.shape, data.dtype, $indices, $segmentIds, true);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentMeanConfig: KernelConfig = {\n kernelName: SparseSegmentMean,\n backendName: 'webgl',\n kernelFunc: sparseSegmentMean as unknown 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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Rank, SparseToDense, SparseToDenseAttrs, SparseToDenseInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {scatterImplCPU} from '../kernel_utils/shared';\nimport {ScatterProgram} from '../scatter_gpu';\n\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, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(sparseValues, sparseIndices, outputShape);\n const sumDupeIndices = false;\n\n if (sparseValues.dtype === 'string') {\n const indicesBuf = backend.bufferSync(sparseIndices);\n const updatesBuf = backend.bufferSync(sparseValues);\n const $defaultValue = util.decodeString(\n backend.readSync(defaultValue.dataId)[0] as Uint8Array);\n const outBuf = scatterImplCPU(\n indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates,\n sliceRank, strides, $defaultValue, sumDupeIndices);\n return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);\n }\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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Sqrt} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {sqrtImplCPU} from '../kernel_utils/shared';\n\nconst SQRT = `return sqrt(x);`;\n\nexport const sqrt = unaryKernelFunc(\n {opSnippet: SQRT, packedOpSnippet: SQRT, cpuKernelImpl: sqrtImplCPU});\n\nexport const sqrtConfig: KernelConfig = {\n kernelName: Sqrt,\n backendName: 'webgl',\n kernelFunc: sqrt as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, NamedAttrMap, StaticRegexReplace, StaticRegexReplaceAttrs, StaticRegexReplaceInputs, TensorInfo} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {staticRegexReplaceImplCPU} from '../kernel_utils/shared';\n\nexport function staticRegexReplace(args: {\n inputs: StaticRegexReplaceInputs,\n backend: MathBackendWebGL,\n attrs: StaticRegexReplaceAttrs,\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n\n if (x.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n\n const $x = backend.readSync(x.dataId) as Uint8Array[];\n\n const stringInput = backend_util.fromUint8ToStringArray($x);\n const output = staticRegexReplaceImplCPU(stringInput, 'string',\n attrs as unknown as NamedAttrMap);\n\n return backend.makeTensorInfo(x.shape, 'string', output);\n}\n\nexport const staticRegexReplaceConfig: KernelConfig = {\n kernelName: StaticRegexReplace,\n backendName: 'webgl',\n kernelFunc: staticRegexReplace as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, 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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class StridedSliceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(begin: number[], strides: number[], size: number[]) {\n this.outputShape = size;\n const rank = size.length;\n const inputDtype = getCoordsDataType(size.length);\n const dtype = getCoordsDataType(size.length);\n\n let newCoords = '';\n if (rank === 1) {\n newCoords = 'coords * strides + begin';\n } else {\n let outputAxis = 0;\n newCoords =\n size.map((_, i) => {\n outputAxis++;\n return size.length === 1 ?\n `coords * strides[${i}] + begin[${i}]` :\n `coords[${outputAxis - 1}] * strides[${i}] + begin[${i}]`;\n })\n .join(',');\n }\n\n this.userCode = `\n ${inputDtype} begin = ${inputDtype}(${begin});\n ${inputDtype} strides = ${inputDtype}(${strides});\n\n void main() {\n ${dtype} coords = getOutputCoords();\n setOutput(getX(${newCoords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, KernelConfig, KernelFunc, Rank, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorBuffer, TensorInfo, TypedArray, util} 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 {\n finalShapeSparse,\n finalShape,\n isIdentity,\n sliceDim0,\n isSimpleSlice,\n begin: $begin,\n end: $end,\n strides: $strides\n } =\n slice_util.sliceInfo(\n x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask);\n\n let result;\n\n if (isIdentity) {\n // Optimization #1, slice is a no-op plus reshape\n result = reshape({inputs: {x}, backend, attrs: {shape: finalShape}});\n } else if (sliceDim0 || isSimpleSlice) {\n // Optimization #2, slice is memory contiguous (only occurs in dim 0)\n util.assert(\n x.shape.length >= 1,\n () => `Input must have rank at least 1, got: ${x.shape.length}`);\n\n const size = slice_util.computeOutShape($begin, $end, $strides);\n // To tolerate begin[0] > end[0] (a 0-output slice), we min(begin, end).\n const sliced = slice({inputs: {x}, backend, attrs: {begin: $begin, size}});\n result =\n reshape({inputs: {x: sliced}, backend, attrs: {shape: finalShape}});\n backend.disposeIntermediateTensorInfo(sliced);\n } else {\n const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);\n if (shouldExecuteOnCPU) {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const values = backend.readSync(x.dataId) as TypedArray;\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const xBuf = buffer(x.shape, x.dtype, values) as TensorBuffer;\n const resultValues =\n stridedSliceImplCPU(finalShapeSparse, xBuf, $strides, $begin);\n result = backend.makeTensorInfo(finalShape, x.dtype, resultValues.values);\n } else {\n const program =\n new StridedSliceProgram($begin, $strides, finalShapeSparse);\n result = backend.runWebGLProgram(program, [x], x.dtype);\n }\n }\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: finalShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n kernelName: StridedSlice,\n backendName: 'webgl',\n kernelFunc: stridedSlice as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringNGrams, StringNGramsAttrs, StringNGramsInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringNGramsImplCPU} from '../kernel_utils/shared';\n\nexport function stringNGrams(args: {\n inputs: StringNGramsInputs,\n backend: MathBackendWebGL,\n attrs: StringNGramsAttrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {\n separator,\n nGramWidths,\n leftPad,\n rightPad,\n padWidth,\n preserveShortSequences\n } = attrs;\n const {data, dataSplits} = inputs;\n const $data = backend.readSync(data.dataId) as Uint8Array[];\n const $dataSplits = backend.readSync(dataSplits.dataId) as Int32Array;\n\n const [nGrams, nGramsSplits] = stringNGramsImplCPU(\n $data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences);\n return [\n backend.makeTensorInfo([nGrams.length], 'string', nGrams),\n backend.makeTensorInfo(dataSplits.shape, 'int32', nGramsSplits),\n ];\n}\n\nexport const stringNGramsConfig: KernelConfig = {\n kernelName: StringNGrams,\n backendName: 'webgl',\n kernelFunc: stringNGrams as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringSplit, StringSplitAttrs, StringSplitInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringSplitImplCPU} from '../kernel_utils/shared';\n\nexport function stringSplit(args: {\n inputs: StringSplitInputs,\n backend: MathBackendWebGL,\n attrs: StringSplitAttrs\n}): [TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {skipEmpty} = attrs;\n const {input, delimiter} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (input.shape.length !== 1) {\n throw new Error(`Input must be a vector, got shape: ${input.shape}`);\n }\n if (delimiter.shape.length !== 0) {\n throw new Error(\n `Delimiter must be a scalar, got shape: ${delimiter.shape}`);\n }\n\n const $input = backend.readSync(input.dataId) as Uint8Array[];\n const $delimiter = backend.readSync(delimiter.dataId)[0] as Uint8Array;\n\n const [indices, values, shape] =\n stringSplitImplCPU($input, $delimiter, skipEmpty);\n const outputSize = values.length;\n return [\n backend.makeTensorInfo([outputSize, 2], 'int32', indices),\n backend.makeTensorInfo([outputSize], 'string', values),\n backend.makeTensorInfo([2], 'int32', new Int32Array(shape))\n ];\n}\n\nexport const stringSplitConfig: KernelConfig = {\n kernelName: StringSplit,\n backendName: 'webgl',\n kernelFunc: stringSplit as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringToHashBucketFastImplCPU} from '../kernel_utils/shared';\n\nexport function stringToHashBucketFast(args: {\n inputs: StringToHashBucketFastInputs,\n backend: MathBackendWebGL,\n attrs: StringToHashBucketFastAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {numBuckets} = attrs;\n const {input} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (numBuckets <= 0) {\n throw new Error(`Number of buckets must be at least 1`);\n }\n\n const $input = backend.readSync(input.dataId) as Uint8Array[];\n\n const output = stringToHashBucketFastImplCPU($input, numBuckets);\n return backend.makeTensorInfo(input.shape, 'int32', output);\n}\n\nexport const stringToHashBucketFastConfig: KernelConfig = {\n kernelName: StringToHashBucketFast,\n backendName: 'webgl',\n kernelFunc: stringToHashBucketFast as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, 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 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, TensorInfo, TensorScatterUpdate, TensorScatterUpdateAttrs, TensorScatterUpdateInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ScatterProgram} from '../scatter_gpu';\n\nimport {reshape} from './Reshape';\n\nexport function tensorScatterUpdate(args: {\n inputs: TensorScatterUpdateInputs,\n backend: MathBackendWebGL,\n attrs: TensorScatterUpdateAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {tensor, indices, updates} = inputs;\n const {} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(updates, indices, tensor.shape);\n\n const flattenShape = [outputSize / sliceSize, sliceSize];\n\n if (outputSize === 0) {\n return backend.makeTensorInfo(tensor.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 const flattenTensor =\n reshape({inputs: {x: tensor}, backend, attrs: {shape: flattenShape}});\n const program = new ScatterProgram(\n numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length,\n strides, flattenShape, false, true);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndices, flattenTensor], flattenTensor.dtype);\n\n const reshaped =\n reshape({inputs: {x: res}, backend, attrs: {shape: tensor.shape}});\n\n backend.disposeIntermediateTensorInfo(flattenIndices);\n backend.disposeIntermediateTensorInfo(flattenX);\n backend.disposeIntermediateTensorInfo(flattenTensor);\n backend.disposeIntermediateTensorInfo(res);\n\n return reshaped;\n}\n\nexport const tensorScatterUpdateConfig: KernelConfig = {\n kernelName: TensorScatterUpdate,\n backendName: 'webgl',\n kernelFunc: tensorScatterUpdate as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TileProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], reps: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[i] * reps[i];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const sourceCoords = getSourceCoords(aShape);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${sourceCoords}));\n }\n `;\n }\n}\n\nfunction getSourceCoords(aShape: number[]): string {\n const rank = aShape.length;\n if (rank > 5) {\n throw Error(`Tile for rank ${rank} is not yet supported`);\n }\n if (rank === 1) {\n return `imod(resRC, ${aShape[0]})`;\n }\n\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u'];\n\n const sourceCoords = [];\n for (let i = 0; i < aShape.length; i++) {\n sourceCoords.push(`imod(${currentCoords[i]}, ${aShape[i]})`);\n }\n return sourceCoords.join();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, KernelConfig, KernelFunc, TensorInfo, Tile, TileAttrs, TileInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {tileImplCPU} from '../kernel_utils/shared';\nimport {TileProgram} from '../tile_gpu';\n\nexport function tile(\n params: {inputs: TileInputs, backend: MathBackendWebGL, attrs: TileAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = params;\n const {x} = inputs;\n const {reps} = attrs;\n\n // tile gpu program cannot handle rank > 5 case.\n if (x.dtype === 'string' || x.shape.length > 5) {\n // Even thought string tensor is always on CPU, just to be consistent on how\n // to access tensor data.\n const data = backend.readSync(x.dataId);\n const value = x.dtype === 'string' ?\n (data as Uint8Array[]).map(d => util.decodeString(d)) :\n data as TypedArray;\n const buf = buffer(x.shape, x.dtype, value);\n const outBuf = tileImplCPU(buf, reps);\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n }\n\n const program = new TileProgram(x.shape, reps);\n const output = backend.runWebGLProgram(program, [x], x.dtype);\n\n return output;\n}\n\nexport const tileConfig: KernelConfig = {\n kernelName: Tile,\n backendName: 'webgl',\n kernelFunc: tile as unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\n// Based on Algorithm 2 of Bitonic Top K, ref:\n// https://anilshanbhag.in/static/papers/gputopk_sigmod18.pdf\n// The original algorithm is based on computing the top K only, however\n// since for TFJS we require the indices of the top K values as well then the\n// algorithm found here is a bit modified. Rather than producing the values\n// at each step, the indices containing the top K are generated instead.\n// The output values are not generated to reduce the number of outputs in the\n// GPU, the values can easily be retrieved from the indices using a gather\n// op.\nexport class SwapProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n // |n| Size of the original input of TopK.\n // |firstPass|indicates if this is the first time swap is being used which\n // means no indices input containing the top K is present yet.\n // |inc| Swaps pairs of indices (0, inc), (1, inc + 1), (2, inc + 2) ...\n customUniforms = [\n {name: 'n', type: 'int' as UniformType},\n {name: 'firstPass', type: 'int' as UniformType},\n {name: 'negativeInf', type: 'float' as UniformType},\n {name: 'dir', type: 'int' as UniformType},\n {name: 'inc', type: 'int' as UniformType}\n ];\n\n /**\n * @param shape desired output shape (can be larger than input shape, output\n * will be padded with -Infinity)\n */\n constructor(shape: number[]) {\n this.outputShape = shape;\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // We compare elements pair-wise within a group of size 2 * inc.\n // The comparing rule for each group alternates between ascending\n // and descending. Within each group, we compare each pair at\n // positions i and i+inc. To decide whether an element at position i\n // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n // inc, it is in the first half of the group, we denote it as x0,\n // otherwise we denote it as x1.\n // For example, as shown in the Bitonic top K paper referenced above,\n // Figure5(a) shows that element[1] is in the\n // second half of the group when group size is 2, but it is in the\n // first half of the group when group size is 4.\n\n bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n // Denotes which direction indices are in (ascending or descending).\n bool reverse = imod(elemIdx, 2 * dir) >= dir;\n bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) { // Elements in opposite order of direction\n int iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutput(float(i0));\n } else {\n setOutput(float(i1));\n }\n }\n `;\n }\n}\n\nexport class MergeProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n // |n| Size of the original input of TopK\n // |firstPass| indicates if this is the first time swap is being used which\n // means no indices input containing the top K is present yet.\n // |k| Top k elements desired\n customUniforms = [\n {name: 'n', type: 'int' as UniformType},\n {name: 'firstPass', type: 'int' as UniformType},\n {name: 'k', type: 'int' as UniformType}\n ];\n\n /**\n * @param shape desired output shape (must be half of the input size)\n */\n constructor(shape: number[]) {\n this.outputShape = shape;\n\n this.userCode = `\n void main() {\n // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),\n // we only need to output the indices at positions |, the indices at\n // positions _ can be thrown away, see Figure5(b) After Phase 2\n // (Merge phase) in the Bitonic Top K paper referenced above.\n // For example, the paper shows we only need to output the orange bars.\n // The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back\n // to the previous sequence to find the corresponding value,\n // we need to double the index. When we double the index,\n // we basically interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n // of each 2k positions by - elemIdx % k. E.g. for output at\n // index 4,5,6,7, we want to get the corresponding element at\n // original index 8,9,10,11, for output at index 8,9,10,11,\n // we want to get the corresponding element at original index\n // 16,17,18,19, so on and so forth.\n\n int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n float x0 = getX(batch, i0);\n float x1 = i1 < n ? getX(batch, i1) : x0;\n\n setOutput(x0 >= x1 ? float(i0) : float(i1));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, NumericDataType, TensorInfo, TopK, TopKAttrs, TopKInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {topKImplCPU} from '../kernel_utils/shared';\nimport {MergeProgram, SwapProgram} from '../top_k_gpu';\nimport {fill} from './Fill';\nimport {gatherV2} from './GatherV2';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nfunction disposeIntermediateTensorInfoOrNull(\n backend: MathBackendWebGL, tensorInfo: TensorInfo) {\n if (tensorInfo !== null) {\n backend.disposeIntermediateTensorInfo(tensorInfo);\n }\n}\n\nfunction roundUpToPow2(num: number) {\n let pow2 = 1;\n while (pow2 < num) {\n pow2 *= 2;\n }\n return pow2;\n}\n\n// Based on Algorithm 2 of Bitonic Top K, ref:\n// https://anilshanbhag.in/static/papers/gputopk_sigmod18.pdf\nexport function topK(\n args: {inputs: TopKInputs, backend: MathBackendWebGL, attrs: TopKAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {k, sorted} = attrs;\n\n // Empirically determined constant used to determine last dim threshold for\n // handing off execution to the CPU.\n const TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD =\n env().getNumber('TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD');\n\n // Empirically determined constant used to determine k threshold for handing\n // off execution to the CPU.\n const TOPK_K_CPU_HANDOFF_THRESHOLD =\n env().getNumber('TOPK_K_CPU_HANDOFF_THRESHOLD');\n\n const xShape = x.shape;\n const lastDim = xShape[xShape.length - 1];\n\n if (backend.shouldExecuteOnCPU([x]) ||\n lastDim < TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD ||\n k > TOPK_K_CPU_HANDOFF_THRESHOLD) {\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const [allTopKVals, allTopKIndices] =\n topKImplCPU(xVals, xShape, x.dtype as NumericDataType, k, sorted);\n\n return [\n backend.makeTensorInfo(\n allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),\n backend.makeTensorInfo(\n allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)\n ];\n }\n\n if (k === 0) {\n xShape[xShape.length - 1] = 0;\n return [\n backend.makeTensorInfo(xShape, x.dtype, []),\n backend.makeTensorInfo(xShape, 'int32', [])\n ];\n }\n\n if (lastDim === 1 /* firstPass */) {\n return [\n x, fill({attrs: {shape: xShape, dtype: 'int32', value: 0}, backend})\n ];\n }\n\n // Eagerly unpack x input since it is passed in to all the shaders which\n // require unpacked inputs.\n const xtexData = backend.texData.get(x.dataId);\n const xIsPacked = xtexData !== null && xtexData.isPacked;\n const xUnPacked = xIsPacked ? backend.unpackTensor(x) : x;\n\n // Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.\n const xSize = util.sizeFromShape(xShape);\n const batch = xSize / lastDim;\n const x2D = reshape(\n {inputs: {x: xUnPacked}, attrs: {shape: [batch, lastDim]}, backend});\n\n if (xIsPacked) {\n disposeIntermediateTensorInfoOrNull(backend, xUnPacked);\n }\n\n const kPow2 = roundUpToPow2(k);\n const lastDimPow2 = roundUpToPow2(lastDim);\n\n // Only the indices containing the top K are kept at every step to reduce\n // number of outputs in the GPU algorithms, so once the final set of indices\n // is computed then gather is used to grab the corresponding values\n // from the original input.\n let indices: TensorInfo = null;\n\n // GPU algorithm always takes in an indices input but this input is not used\n // on the first run of a GPU algorithm, therefore if indices is null we simply\n // pass in x2D instead of it but the value will not actually be used\n const getInputs = () => indices === null ? [x2D, x2D] : [x2D, indices];\n\n const runSwap = (dir: number, inc: number, shape: number[]) => {\n const inputs = getInputs();\n const program = new SwapProgram(shape);\n const fistPass = indices === null ? 1 : 0;\n const customValues =\n [[lastDim], [fistPass], [Number.NEGATIVE_INFINITY], [dir], [inc]];\n const prevIndices = indices;\n indices = backend.runWebGLProgram(program, inputs, 'int32', customValues);\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n };\n\n // Step 1: local sort\n for (let len = 1; len < kPow2; len *= 2) {\n const dir = len * 2;\n for (let inc = len; inc >= 1; inc /= 2) {\n runSwap(dir, inc, [batch, lastDimPow2]);\n }\n }\n\n // Step 2: merge\n for (let indicesSize = lastDimPow2; indicesSize > kPow2; indicesSize /= 2) {\n const inputs = getInputs();\n const mergeProgram = new MergeProgram([batch, indicesSize / 2]);\n const firstPass = indices === null ? 1 : 0;\n const customValues = [[lastDim], [firstPass], [kPow2]];\n const prevIndices = indices;\n indices =\n backend.runWebGLProgram(mergeProgram, inputs, 'int32', customValues);\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n\n // Step 3: rebuild\n const len = kPow2 / 2;\n const dir = len * 2;\n for (let inc = len; inc >= 1; inc /= 2) {\n runSwap(dir, inc, indices.shape);\n }\n }\n\n // Keep only the requested top K results instead of kPow2\n let prevIndices = indices;\n indices = slice(\n {inputs: {x: indices}, backend, attrs: {begin: 0, size: [batch, k]}});\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n\n // Gather values on last dimension\n let values = gatherV2(\n {inputs: {x: x2D, indices}, backend, attrs: {axis: 1, batchDims: 1}});\n disposeIntermediateTensorInfoOrNull(backend, x2D);\n\n // Reshape back to the original input shape, except that the last\n // dimension is k.\n const newShape = xShape.slice(0, -1);\n newShape.push(k);\n\n prevIndices = indices;\n indices = reshape({inputs: {x: indices}, attrs: {shape: newShape}, backend});\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n\n const prevValues = values;\n values = reshape({inputs: {x: values}, attrs: {shape: newShape}, backend});\n disposeIntermediateTensorInfoOrNull(backend, prevValues);\n\n return [values, indices];\n}\n\nexport const topKConfig: KernelConfig = {\n kernelName: TopK,\n backendName: 'webgl',\n kernelFunc: topK as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class TransformProgram implements GPGPUProgram {\n variableNames = ['Image', 'Transforms'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n imageHeight: number, imageWidth: number,\n interpolation: 'nearest'|'bilinear',\n fillMode: 'constant'|'reflect'|'wrap'|'nearest', fillValue: number,\n outShape: [number, number, number, number]) {\n this.outputShape = outShape;\n const interpolationModeId = interpolation === 'nearest' ? 1 : 2;\n let fillModeId;\n switch (fillMode) {\n case 'constant':\n fillModeId = 1;\n break;\n case 'reflect':\n fillModeId = 2;\n break;\n case 'wrap':\n fillModeId = 3;\n break;\n case 'nearest':\n fillModeId = 4;\n break;\n default:\n fillModeId = 1;\n break;\n }\n this.userCode = `\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${fillModeId} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${fillModeId} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${fillModeId} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${\n imageHeight} && 0 <= coordX && coordX < ${imageWidth}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${fillValue});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${fillValue});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${imageWidth}));\n float mapY = mapCoord(inY, float(${imageHeight}));\n\n if (${interpolationModeId} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Transform, TransformAttrs, TransformInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {TransformProgram} from '../transform_gpu';\n\nexport function transform(args: {\n inputs: TransformInputs,\n backend: MathBackendWebGL,\n attrs: TransformAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image, transforms} = inputs;\n const {interpolation, fillMode, fillValue, outputShape} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const [outHeight, outWidth] =\n outputShape != null ? outputShape : [imageHeight, imageWidth];\n const outShape =\n [batch, outHeight, outWidth,\n numChannels] as [number, number, number, number];\n\n const program = new TransformProgram(\n imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);\n return backend.runWebGLProgram(program, [image, transforms], 'float32');\n}\n\nexport const transformConfig: KernelConfig = {\n kernelName: Transform,\n backendName: 'webgl',\n kernelFunc: transform as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, 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 unknown as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, 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 unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class SegmentOpProgram implements GPGPUProgram {\n variableNames = ['x', 'segmentIds'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n segOpInfo: backend_util.segment_util.SegOpInfo,\n segOpType: 'unsortedSegmentSum') {\n const windowSize = segOpInfo.windowSize;\n const batchSize = segOpInfo.batchSize;\n const inSize = segOpInfo.inSize;\n const numSegments = segOpInfo.numSegments;\n const outSize = numSegments * Math.ceil(inSize / windowSize);\n this.outputShape = [batchSize, outSize];\n\n const initializationValue = '0.0';\n const returnValue = `sumValue`;\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n const updateSnippet = `\n sumValue += dot(values, segFilter);\n `;\n\n let checkValueOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkValueOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return initializationValue;\n }\n `;\n }\n\n let checkSegmentIdOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkSegmentIdOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return -1.0;\n }\n `;\n }\n\n this.userCode = `\n const float initializationValue = ${initializationValue};\n\n float getValue(int batch, int inIdx) {\n ${checkValueOutOfBounds}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${checkSegmentIdOutOfBounds}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${numSegments})) * float(${windowSize}));\n int currentSeg = int(mod(float(outIdx), float(${numSegments})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${updateSnippet}\n }\n setOutput(${returnValue});\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, KernelConfig, KernelFunc, sumOutType, TensorInfo, UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SegmentOpProgram} from '../segment_gpu';\n\nimport {range} from './Range';\nimport {reshape} from './Reshape';\nimport {tile} from './Tile';\nimport {transpose} from './Transpose';\n\nexport function unsortedSegmentSum(args: {\n inputs: UnsortedSegmentSumInputs,\n backend: MathBackendWebGL,\n attrs: UnsortedSegmentSumAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, segmentIds} = inputs;\n const {numSegments} = attrs;\n\n const xRank = x.shape.length;\n\n const toDispose = [];\n\n let axis = 0;\n const permutation = backend_util.getAxesPermutation([axis], xRank);\n let permutedX = x;\n if (permutation != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n toDispose.push(permutedX);\n axis = backend_util.getInnerMostAxes(1, xRank)[0];\n }\n\n const outShape = backend_util.segment_util.computeOutShape(\n permutedX.shape, axis, numSegments);\n const inSize = util.sizeFromShape([permutedX.shape[axis]]);\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n toDispose.push(a2D);\n\n const outputDType = sumOutType(x.dtype);\n\n const segOpCompute =\n (x: TensorInfo, segOpType: 'unsortedSegmentSum', segmentIds: TensorInfo,\n dtype: DataType, numSegments: number): TensorInfo => {\n const batchSize = x.shape[0];\n const inSize = x.shape[1];\n const windowSize =\n backend_util.segment_util.segOpComputeOptimalWindowSize(\n inSize, numSegments);\n const segOpInfo = {windowSize, inSize, batchSize, numSegments};\n const program = new SegmentOpProgram(segOpInfo, segOpType);\n const output = backend.compileAndRun(program, [x, segmentIds], dtype);\n toDispose.push(output);\n // No need to run another GPGPU program.\n if (output.shape[1] === numSegments) {\n return output;\n }\n const rangeInfo = range({\n backend,\n attrs: {start: 0, stop: numSegments, step: 1, dtype: 'float32'}\n });\n const tileInfo = tile({\n inputs: {x: rangeInfo},\n backend,\n attrs: {reps: [inSize / windowSize]}\n });\n\n toDispose.push(rangeInfo);\n toDispose.push(tileInfo);\n\n const result =\n segOpCompute(output, segOpType, tileInfo, dtype, numSegments);\n return result;\n };\n\n const segOpResult = segOpCompute(\n a2D, 'unsortedSegmentSum', segmentIds, outputDType, numSegments);\n\n const reshaped =\n reshape({inputs: {x: segOpResult}, backend, attrs: {shape: outShape}});\n\n let result = reshaped;\n if (permutation != null) {\n toDispose.push(reshaped);\n const perm = backend_util.getUndoAxesPermutation(permutation);\n result = transpose({inputs: {x: result}, backend, attrs: {perm}});\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return result;\n}\n\nexport const unsortedSegmentSumConfig: KernelConfig = {\n kernelName: UnsortedSegmentSum,\n backendName: 'webgl',\n kernelFunc: unsortedSegmentSum as unknown as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {KernelConfig, registerKernel} from '@tensorflow/tfjs-core';\n\nimport {_fusedMatMulConfig} from './kernels/_FusedMatMul';\nimport {absConfig} from './kernels/Abs';\nimport {acosConfig} from './kernels/Acos';\nimport {acoshConfig} from './kernels/Acosh';\nimport {addConfig} from './kernels/Add';\nimport {addNConfig} from './kernels/AddN';\nimport {allConfig} from './kernels/All';\nimport {anyConfig} from './kernels/Any';\nimport {argMaxConfig} from './kernels/ArgMax';\nimport {argMinConfig} from './kernels/ArgMin';\nimport {asinConfig} from './kernels/Asin';\nimport {asinhConfig} from './kernels/Asinh';\nimport {atanConfig} from './kernels/Atan';\nimport {atan2Config} from './kernels/Atan2';\nimport {atanhConfig} from './kernels/Atanh';\nimport {avgPoolConfig} from './kernels/AvgPool';\nimport {avgPool3DConfig} from './kernels/AvgPool3D';\nimport {avgPool3DGradConfig} from './kernels/AvgPool3DGrad';\nimport {avgPoolGradConfig} from './kernels/AvgPoolGrad';\nimport {batchMatMulConfig} from './kernels/BatchMatMul';\nimport {batchNormConfig} from './kernels/BatchNorm';\nimport {batchToSpaceNDConfig} from './kernels/BatchToSpaceND';\nimport {bincountConfig} from './kernels/Bincount';\nimport {bitwiseAndConfig} from './kernels/BitwiseAnd';\nimport {broadcastArgsConfig} from './kernels/BroadcastArgs';\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 {cumprodConfig} from './kernels/Cumprod';\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 {maxPool3DGradConfig} from './kernels/MaxPool3DGrad';\nimport {maxPoolGradConfig} from './kernels/MaxPoolGrad';\nimport {maxPoolWithArgmaxConfig} from './kernels/MaxPoolWithArgmax';\nimport {meanConfig} from './kernels/Mean';\nimport {minConfig} from './kernels/Min';\nimport {minimumConfig} from './kernels/Minimum';\nimport {mirrorPadConfig} from './kernels/MirrorPad';\nimport {modConfig} from './kernels/Mod';\nimport {multinomialConfig} from './kernels/Multinomial';\nimport {multiplyConfig} from './kernels/Multiply';\nimport {negConfig} from './kernels/Neg';\nimport {nonMaxSuppressionV3Config} from './kernels/NonMaxSuppressionV3';\nimport {nonMaxSuppressionV4Config} from './kernels/NonMaxSuppressionV4';\nimport {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';\nimport {notEqualConfig} from './kernels/NotEqual';\nimport {oneHotConfig} from './kernels/OneHot';\nimport {onesLikeConfig} from './kernels/OnesLike';\nimport {packConfig} from './kernels/Pack';\nimport {padV2Config} from './kernels/PadV2';\nimport {powConfig} from './kernels/Pow';\nimport {preluConfig} from './kernels/Prelu';\nimport {prodConfig} from './kernels/Prod';\nimport {raggedGatherConfig} from './kernels/RaggedGather';\nimport {raggedRangeConfig} from './kernels/RaggedRange';\nimport {raggedTensorToTensorConfig} from './kernels/RaggedTensorToTensor';\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 {searchSortedConfig} from './kernels/SearchSorted';\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 {staticRegexReplaceConfig} from './kernels/StaticRegexReplace';\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 {tensorScatterUpdateConfig} from './kernels/TensorScatterUpdate';\nimport {tileConfig} from './kernels/Tile';\nimport {topKConfig} from './kernels/TopK';\nimport {transformConfig} from './kernels/Transform';\nimport {transposeConfig} from './kernels/Transpose';\nimport {uniqueConfig} from './kernels/Unique';\nimport {unpackConfig} from './kernels/Unpack';\nimport {unsortedSegmentSumConfig} from './kernels/UnsortedSegmentSum';\nimport {zerosLikeConfig} from './kernels/ZerosLike';\n\n// List all kernel configs here\nconst kernelConfigs: KernelConfig[] = [\n _fusedMatMulConfig,\n absConfig,\n acosConfig,\n acoshConfig,\n addConfig,\n addNConfig,\n allConfig,\n anyConfig,\n argMaxConfig,\n argMinConfig,\n asinConfig,\n asinhConfig,\n atanConfig,\n atan2Config,\n atanhConfig,\n avgPoolConfig,\n avgPool3DConfig,\n avgPool3DGradConfig,\n avgPoolGradConfig,\n batchMatMulConfig,\n batchNormConfig,\n batchToSpaceNDConfig,\n bincountConfig,\n bitwiseAndConfig,\n broadcastArgsConfig,\n castConfig,\n ceilConfig,\n clipByValueConfig,\n complexConfig,\n complexAbsConfig,\n concatConfig,\n conv2DConfig,\n conv2DBackpropFilterConfig,\n conv2DBackpropInputConfig,\n conv3DConfig,\n conv3DBackpropFilterV2Config,\n conv3DBackpropInputConfig,\n cosConfig,\n coshConfig,\n cropAndResizeConfig,\n cumprodConfig,\n cumsumConfig,\n denseBincountConfig,\n depthToSpaceConfig,\n depthwiseConv2dNativeConfig,\n depthwiseConv2dNativeBackpropFilterConfig,\n depthwiseConv2dNativeBackpropInputConfig,\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 logConfig,\n log1pConfig,\n logicalAndConfig,\n logicalNotConfig,\n logicalOrConfig,\n LRNConfig,\n LRNGradConfig,\n maxConfig,\n maximumConfig,\n maxPoolConfig,\n maxPool3DConfig,\n maxPool3DGradConfig,\n maxPoolGradConfig,\n maxPoolWithArgmaxConfig,\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 raggedGatherConfig,\n raggedRangeConfig,\n raggedTensorToTensorConfig,\n rangeConfig,\n realConfig,\n realDivConfig,\n reciprocalConfig,\n reluConfig,\n relu6Config,\n reshapeConfig,\n resizeBilinearConfig,\n resizeBilinearGradConfig,\n resizeNearestNeighborConfig,\n resizeNearestNeighborGradConfig,\n reverseConfig,\n rotateWithOffsetConfig,\n roundConfig,\n rsqrtConfig,\n scatterNdConfig,\n searchSortedConfig,\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 staticRegexReplaceConfig,\n stepConfig,\n stridedSliceConfig,\n stringNGramsConfig,\n stringSplitConfig,\n stringToHashBucketFastConfig,\n subConfig,\n sumConfig,\n tanConfig,\n tanhConfig,\n tensorScatterUpdateConfig,\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","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.17.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 '@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.\nexport * from '@tensorflow/tfjs-backend-cpu';\nexport * from '@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 * Locale character mapping rules.\n */\ninterface Locale {\n regexp: RegExp;\n map: Record;\n}\n\n/**\n * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt\n */\nconst SUPPORTED_LOCALE: Record = {\n tr: {\n regexp: /\\u0130|\\u0049|\\u0049\\u0307/g,\n map: {\n İ: \"\\u0069\",\n I: \"\\u0131\",\n İ: \"\\u0069\",\n },\n },\n az: {\n regexp: /\\u0130/g,\n map: {\n İ: \"\\u0069\",\n I: \"\\u0131\",\n İ: \"\\u0069\",\n },\n },\n lt: {\n regexp: /\\u0049|\\u004A|\\u012E|\\u00CC|\\u00CD|\\u0128/g,\n map: {\n I: \"\\u0069\\u0307\",\n J: \"\\u006A\\u0307\",\n Į: \"\\u012F\\u0307\",\n Ì: \"\\u0069\\u0307\\u0300\",\n Í: \"\\u0069\\u0307\\u0301\",\n Ĩ: \"\\u0069\\u0307\\u0303\",\n },\n },\n};\n\n/**\n * Localized lower case.\n */\nexport function localeLowerCase(str: string, locale: string) {\n const lang = SUPPORTED_LOCALE[locale.toLowerCase()];\n if (lang) return lowerCase(str.replace(lang.regexp, (m) => lang.map[m]));\n return lowerCase(str);\n}\n\n/**\n * Lower case as a function.\n */\nexport function lowerCase(str: string) {\n return str.toLowerCase();\n}\n","import { lowerCase } from \"lower-case\";\n\nexport interface Options {\n splitRegexp?: RegExp | RegExp[];\n stripRegexp?: RegExp | RegExp[];\n delimiter?: string;\n transform?: (part: string, index: number, parts: string[]) => string;\n}\n\n// Support camel case (\"camelCase\" -> \"camel Case\" and \"CAMELCase\" -> \"CAMEL Case\").\nconst DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];\n\n// Remove all non-word characters.\nconst DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;\n\n/**\n * Normalize the string into something other libraries can manipulate easier.\n */\nexport function noCase(input: string, options: Options = {}) {\n const {\n splitRegexp = DEFAULT_SPLIT_REGEXP,\n stripRegexp = DEFAULT_STRIP_REGEXP,\n transform = lowerCase,\n delimiter = \" \",\n } = options;\n\n let result = replace(\n replace(input, splitRegexp, \"$1\\0$2\"),\n stripRegexp,\n \"\\0\"\n );\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n // Transform each token independently.\n return result.slice(start, end).split(\"\\0\").map(transform).join(delimiter);\n}\n\n/**\n * Replace `re` in the input string with the replacement value.\n */\nfunction replace(input: string, re: RegExp | RegExp[], value: string) {\n if (re instanceof RegExp) return input.replace(re, value);\n return re.reduce((input, re) => input.replace(re, value), input);\n}\n","import { noCase, Options } from \"no-case\";\n\nexport { Options };\n\nexport function pascalCaseTransform(input: string, index: number) {\n const firstChar = input.charAt(0);\n const lowerChars = input.substr(1).toLowerCase();\n if (index > 0 && firstChar >= \"0\" && firstChar <= \"9\") {\n return `_${firstChar}${lowerChars}`;\n }\n return `${firstChar.toUpperCase()}${lowerChars}`;\n}\n\nexport function pascalCaseTransformMerge(input: string) {\n return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();\n}\n\nexport function pascalCase(input: string, options: Options = {}) {\n return noCase(input, {\n delimiter: \"\",\n transform: pascalCaseTransform,\n ...options,\n });\n}\n","import {\n pascalCase,\n pascalCaseTransform,\n pascalCaseTransformMerge,\n Options,\n} from \"pascal-case\";\n\nexport { Options };\n\nexport function camelCaseTransform(input: string, index: number) {\n if (index === 0) return input.toLowerCase();\n return pascalCaseTransform(input, index);\n}\n\nexport function camelCaseTransformMerge(input: string, index: number) {\n if (index === 0) return input.toLowerCase();\n return pascalCaseTransformMerge(input);\n}\n\nexport function camelCase(input: string, options: Options = {}) {\n return pascalCase(input, {\n transform: camelCaseTransform,\n ...options,\n });\n}\n","/**\n * Upper case the first character of an input string.\n */\nexport function upperCaseFirst(input: string) {\n return input.charAt(0).toUpperCase() + input.substr(1);\n}\n","import { noCase, Options } from \"no-case\";\nimport { upperCaseFirst } from \"upper-case-first\";\n\nexport { Options };\n\nexport function capitalCaseTransform(input: string) {\n return upperCaseFirst(input.toLowerCase());\n}\n\nexport function capitalCase(input: string, options: Options = {}) {\n return noCase(input, {\n delimiter: \" \",\n transform: capitalCaseTransform,\n ...options,\n });\n}\n","/**\n * Locale character mapping rules.\n */\ninterface Locale {\n regexp: RegExp;\n map: Record;\n}\n\n/**\n * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt\n */\nconst SUPPORTED_LOCALE: Record = {\n tr: {\n regexp: /[\\u0069]/g,\n map: {\n i: \"\\u0130\",\n },\n },\n az: {\n regexp: /[\\u0069]/g,\n map: {\n i: \"\\u0130\",\n },\n },\n lt: {\n regexp: /[\\u0069\\u006A\\u012F]\\u0307|\\u0069\\u0307[\\u0300\\u0301\\u0303]/g,\n map: {\n i̇: \"\\u0049\",\n j̇: \"\\u004A\",\n į̇: \"\\u012E\",\n i̇̀: \"\\u00CC\",\n i̇́: \"\\u00CD\",\n i̇̃: \"\\u0128\",\n },\n },\n};\n\n/**\n * Localized upper case.\n */\nexport function localeUpperCase(str: string, locale: string) {\n const lang = SUPPORTED_LOCALE[locale.toLowerCase()];\n if (lang) return upperCase(str.replace(lang.regexp, (m) => lang.map[m]));\n return upperCase(str);\n}\n\n/**\n * Upper case as a function.\n */\nexport function upperCase(str: string) {\n return str.toUpperCase();\n}\n","import { noCase, Options } from \"no-case\";\nimport { upperCase } from \"upper-case\";\n\nexport { Options };\n\nexport function constantCase(input: string, options: Options = {}) {\n return noCase(input, {\n delimiter: \"_\",\n transform: upperCase,\n ...options,\n });\n}\n","import { noCase, Options } from \"no-case\";\n\nexport { Options };\n\nexport function dotCase(input: string, options: Options = {}) {\n return noCase(input, {\n delimiter: \".\",\n ...options,\n });\n}\n","import { capitalCase, Options } from \"capital-case\";\n\nexport { Options };\n\nexport function headerCase(input: string, options: Options = {}) {\n return capitalCase(input, {\n delimiter: \"-\",\n ...options,\n });\n}\n","import { dotCase, Options } from \"dot-case\";\n\nexport { Options };\n\nexport function paramCase(input: string, options: Options = {}) {\n return dotCase(input, {\n delimiter: \"-\",\n ...options,\n });\n}\n","import { dotCase, Options } from \"dot-case\";\n\nexport { Options };\n\nexport function pathCase(input: string, options: Options = {}) {\n return dotCase(input, {\n delimiter: \"/\",\n ...options,\n });\n}\n","import { noCase, Options } from \"no-case\";\nimport { upperCaseFirst } from \"upper-case-first\";\n\nexport { Options };\n\nexport function sentenceCaseTransform(input: string, index: number) {\n const result = input.toLowerCase();\n if (index === 0) return upperCaseFirst(result);\n return result;\n}\n\nexport function sentenceCase(input: string, options: Options = {}) {\n return noCase(input, {\n delimiter: \" \",\n transform: sentenceCaseTransform,\n ...options,\n });\n}\n","import { dotCase, Options } from \"dot-case\";\n\nexport { Options };\n\nexport function snakeCase(input: string, options: Options = {}) {\n return dotCase(input, {\n delimiter: \"_\",\n ...options,\n });\n}\n","'use strict';\n\n/******************************************************************************\n * Created 2008-08-19.\n *\n * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.\n *\n * Copyright (C) 2008\n * Wyatt Baldwin \n * All rights reserved\n *\n * Licensed under the MIT license.\n *\n * http://www.opensource.org/licenses/mit-license.php\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 *****************************************************************************/\nvar dijkstra = {\n single_source_shortest_paths: function(graph, s, d) {\n // Predecessor map for each node that has been encountered.\n // node ID => predecessor node ID\n var predecessors = {};\n\n // Costs of shortest paths from s to all nodes encountered.\n // node ID => cost\n var costs = {};\n costs[s] = 0;\n\n // Costs of shortest paths from s to all nodes encountered; differs from\n // `costs` in that it provides easy access to the node that currently has\n // the known shortest path from s.\n // XXX: Do we actually need both `costs` and `open`?\n var open = dijkstra.PriorityQueue.make();\n open.push(s, 0);\n\n var closest,\n u, v,\n cost_of_s_to_u,\n adjacent_nodes,\n cost_of_e,\n cost_of_s_to_u_plus_cost_of_e,\n cost_of_s_to_v,\n first_visit;\n while (!open.empty()) {\n // In the nodes remaining in graph that have a known cost from s,\n // find the node, u, that currently has the shortest path from s.\n closest = open.pop();\n u = closest.value;\n cost_of_s_to_u = closest.cost;\n\n // Get nodes adjacent to u...\n adjacent_nodes = graph[u] || {};\n\n // ...and explore the edges that connect u to those nodes, updating\n // the cost of the shortest paths to any or all of those nodes as\n // necessary. v is the node across the current edge from u.\n for (v in adjacent_nodes) {\n if (adjacent_nodes.hasOwnProperty(v)) {\n // Get the cost of the edge running from u to v.\n cost_of_e = adjacent_nodes[v];\n\n // Cost of s to u plus the cost of u to v across e--this is *a*\n // cost from s to v that may or may not be less than the current\n // known cost to v.\n cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;\n\n // If we haven't visited v yet OR if the current known cost from s to\n // v is greater than the new cost we just found (cost of s to u plus\n // cost of u to v across e), update v's cost in the cost list and\n // update v's predecessor in the predecessor list (it's now u).\n cost_of_s_to_v = costs[v];\n first_visit = (typeof costs[v] === 'undefined');\n if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {\n costs[v] = cost_of_s_to_u_plus_cost_of_e;\n open.push(v, cost_of_s_to_u_plus_cost_of_e);\n predecessors[v] = u;\n }\n }\n }\n }\n\n if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {\n var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');\n throw new Error(msg);\n }\n\n return predecessors;\n },\n\n extract_shortest_path_from_predecessor_list: function(predecessors, d) {\n var nodes = [];\n var u = d;\n var predecessor;\n while (u) {\n nodes.push(u);\n predecessor = predecessors[u];\n u = predecessors[u];\n }\n nodes.reverse();\n return nodes;\n },\n\n find_path: function(graph, s, d) {\n var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);\n return dijkstra.extract_shortest_path_from_predecessor_list(\n predecessors, d);\n },\n\n /**\n * A very naive priority queue implementation.\n */\n PriorityQueue: {\n make: function (opts) {\n var T = dijkstra.PriorityQueue,\n t = {},\n key;\n opts = opts || {};\n for (key in T) {\n if (T.hasOwnProperty(key)) {\n t[key] = T[key];\n }\n }\n t.queue = [];\n t.sorter = opts.sorter || T.default_sorter;\n return t;\n },\n\n default_sorter: function (a, b) {\n return a.cost - b.cost;\n },\n\n /**\n * Add a new item to the queue and ensure the highest priority element\n * is at the front of the queue.\n */\n push: function (value, cost) {\n var item = {value: value, cost: cost};\n this.queue.push(item);\n this.queue.sort(this.sorter);\n },\n\n /**\n * Return the highest priority element in the queue.\n */\n pop: function () {\n return this.queue.shift();\n },\n\n empty: function () {\n return this.queue.length === 0;\n }\n }\n};\n\n\n// node.js module exports\nif (typeof module !== 'undefined') {\n module.exports = dijkstra;\n}\n","'use strict'\n\nmodule.exports = function encodeUtf8 (input) {\n var result = []\n var size = input.length\n\n for (var index = 0; index < size; index++) {\n var point = input.charCodeAt(index)\n\n if (point >= 0xD800 && point <= 0xDBFF && size > index + 1) {\n var second = input.charCodeAt(index + 1)\n\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n point = (point - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n index += 1\n }\n }\n\n // US-ASCII\n if (point < 0x80) {\n result.push(point)\n continue\n }\n\n // 2-byte UTF-8\n if (point < 0x800) {\n result.push((point >> 6) | 192)\n result.push((point & 63) | 128)\n continue\n }\n\n // 3-byte UTF-8\n if (point < 0xD800 || (point >= 0xE000 && point < 0x10000)) {\n result.push((point >> 12) | 224)\n result.push(((point >> 6) & 63) | 128)\n result.push((point & 63) | 128)\n continue\n }\n\n // 4-byte UTF-8\n if (point >= 0x10000 && point <= 0x10FFFF) {\n result.push((point >> 18) | 240)\n result.push(((point >> 12) & 63) | 128)\n result.push(((point >> 6) & 63) | 128)\n result.push((point & 63) | 128)\n continue\n }\n\n // Invalid character\n result.push(0xEF, 0xBF, 0xBD)\n }\n\n return new Uint8Array(result).buffer\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\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar invariant = function(condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error(\n 'Minified exception occurred; use the non-minified dev environment ' +\n 'for the full error message and additional helpful warnings.'\n );\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(\n format.replace(/%s/g, function() { return args[argIndex++]; })\n );\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\nmodule.exports = arrayReduce;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arraySome;\n","/** Used to match words composed of alphanumeric characters. */\nvar reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n/**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction asciiWords(string) {\n return string.match(reAsciiWord) || [];\n}\n\nmodule.exports = asciiWords;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignMergeValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nmodule.exports = baseCreate;\n","var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n","var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n","var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nmodule.exports = baseIsMatch;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nmodule.exports = baseIteratee;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n","var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n","var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nmodule.exports = baseMatches;\n","var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nmodule.exports = baseMatchesProperty;\n","var Stack = require('./_Stack'),\n assignMergeValue = require('./_assignMergeValue'),\n baseFor = require('./_baseFor'),\n baseMergeDeep = require('./_baseMergeDeep'),\n isObject = require('./isObject'),\n keysIn = require('./keysIn'),\n safeGet = require('./_safeGet');\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nmodule.exports = baseMerge;\n","var assignMergeValue = require('./_assignMergeValue'),\n cloneBuffer = require('./_cloneBuffer'),\n cloneTypedArray = require('./_cloneTypedArray'),\n copyArray = require('./_copyArray'),\n initCloneObject = require('./_initCloneObject'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLikeObject = require('./isArrayLikeObject'),\n isBuffer = require('./isBuffer'),\n isFunction = require('./isFunction'),\n isObject = require('./isObject'),\n isPlainObject = require('./isPlainObject'),\n isTypedArray = require('./isTypedArray'),\n safeGet = require('./_safeGet'),\n toPlainObject = require('./toPlainObject');\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nmodule.exports = baseMergeDeep;\n","var baseGet = require('./_baseGet'),\n baseSet = require('./_baseSet'),\n castPath = require('./_castPath');\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n}\n\nmodule.exports = basePickBy;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nmodule.exports = basePropertyDeep;\n","/**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = basePropertyOf;\n","var identity = require('./identity'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n","var assignValue = require('./_assignValue'),\n castPath = require('./_castPath'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nmodule.exports = baseSet;\n","var constant = require('./constant'),\n defineProperty = require('./_defineProperty'),\n identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nmodule.exports = baseSetToString;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n","var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nmodule.exports = cloneBuffer;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nmodule.exports = copyArray;\n","var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nmodule.exports = createAssigner;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n","var arrayReduce = require('./_arrayReduce'),\n deburr = require('./deburr'),\n words = require('./words');\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\";\n\n/** Used to match apostrophes. */\nvar reApos = RegExp(rsApos, 'g');\n\n/**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\nfunction createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n}\n\nmodule.exports = createCompounder;\n","var basePropertyOf = require('./_basePropertyOf');\n\n/** Used to map Latin Unicode letters to basic Latin letters. */\nvar deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n};\n\n/**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\nvar deburrLetter = basePropertyOf(deburredLetters);\n\nmodule.exports = deburrLetter;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalArrays;\n","var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nmodule.exports = equalByTag;\n","var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalObjects;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbolsIn = require('./_getSymbolsIn'),\n keysIn = require('./keysIn');\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nmodule.exports = getAllKeysIn;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nmodule.exports = getMatchData;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nmodule.exports = getSymbols;\n","var arrayPush = require('./_arrayPush'),\n getPrototype = require('./_getPrototype'),\n getSymbols = require('./_getSymbols'),\n stubArray = require('./stubArray');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nmodule.exports = getSymbolsIn;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n","/** Used to detect strings that need a more robust regexp to match words. */\nvar reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n/**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\nfunction hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n}\n\nmodule.exports = hasUnicodeWord;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var baseCreate = require('./_baseCreate'),\n getPrototype = require('./_getPrototype'),\n isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nmodule.exports = initCloneObject;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n","var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nmodule.exports = mapToArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nmodule.exports = matchesStrictComparable;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nmodule.exports = safeGet;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var baseSetToString = require('./_baseSetToString'),\n shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nmodule.exports = stringToPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\",\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;\n\n/** Used to match complex or compound words. */\nvar reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n].join('|'), 'g');\n\n/**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n}\n\nmodule.exports = unicodeWords;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n","var deburrLetter = require('./_deburrLetter'),\n toString = require('./toString');\n\n/** Used to match Latin Unicode letters (excluding mathematical operators). */\nvar reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n/** Used to compose unicode character classes. */\nvar rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;\n\n/** Used to compose unicode capture groups. */\nvar rsCombo = '[' + rsComboRange + ']';\n\n/**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\nvar reComboMark = RegExp(rsCombo, 'g');\n\n/**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\nfunction deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n}\n\nmodule.exports = deburr;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var isArrayLike = require('./isArrayLike'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\nvar kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n});\n\nmodule.exports = kebabCase;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n","var arrayMap = require('./_arrayMap'),\n baseIteratee = require('./_baseIteratee'),\n basePickBy = require('./_basePickBy'),\n getAllKeysIn = require('./_getAllKeysIn');\n\n/**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\nfunction pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = baseIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n}\n\nmodule.exports = pickBy;\n","var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nmodule.exports = toPlainObject;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","var asciiWords = require('./_asciiWords'),\n hasUnicodeWord = require('./_hasUnicodeWord'),\n toString = require('./toString'),\n unicodeWords = require('./_unicodeWords');\n\n/**\n * Splits `string` into an array of its words.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {RegExp|string} [pattern] The pattern to match words.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the words of `string`.\n * @example\n *\n * _.words('fred, barney, & pebbles');\n * // => ['fred', 'barney', 'pebbles']\n *\n * _.words('fred, barney, & pebbles', /[^, ]+/g);\n * // => ['fred', 'barney', '&', 'pebbles']\n */\nfunction words(string, pattern, guard) {\n string = toString(string);\n pattern = guard ? undefined : pattern;\n\n if (pattern === undefined) {\n return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);\n }\n return string.match(pattern) || [];\n}\n\nmodule.exports = words;\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.} 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.} 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.} 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.} 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.} 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.} 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","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = all;\n\nvar _createChainableTypeChecker = require('./utils/createChainableTypeChecker');\n\nvar _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction all() {\n for (var _len = arguments.length, validators = Array(_len), _key = 0; _key < _len; _key++) {\n validators[_key] = arguments[_key];\n }\n\n function allPropTypes() {\n for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n var error = null;\n\n validators.forEach(function (validator) {\n if (error != null) {\n return;\n }\n\n var result = validator.apply(undefined, args);\n if (result != null) {\n error = result;\n }\n });\n\n return error;\n }\n\n return (0, _createChainableTypeChecker2.default)(allPropTypes);\n}\nmodule.exports = exports['default'];","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createChainableTypeChecker;\n/**\n * Copyright 2013-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n */\n\n// Mostly taken from ReactPropTypes.\n\nfunction createChainableTypeChecker(validate) {\n function checkType(isRequired, props, propName, componentName, location, propFullName) {\n var componentNameSafe = componentName || '<>';\n var propFullNameSafe = propFullName || propName;\n\n if (props[propName] == null) {\n if (isRequired) {\n return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.'));\n }\n\n return null;\n }\n\n for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {\n args[_key - 6] = arguments[_key];\n }\n\n return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args));\n }\n\n var chainedCheckType = checkType.bind(null, false);\n chainedCheckType.isRequired = checkType.bind(null, true);\n\n return chainedCheckType;\n}\nmodule.exports = exports['default'];","/**\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 bigint: 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\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 * 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","\nconst canPromise = require('./can-promise')\n\nconst QRCode = require('./core/qrcode')\nconst CanvasRenderer = require('./renderer/canvas')\nconst SvgRenderer = require('./renderer/svg-tag.js')\n\nfunction renderCanvas (renderFunc, canvas, text, opts, cb) {\n const args = [].slice.call(arguments, 1)\n const argsNum = args.length\n const isLastArgCb = typeof args[argsNum - 1] === 'function'\n\n if (!isLastArgCb && !canPromise()) {\n throw new Error('Callback required as last argument')\n }\n\n if (isLastArgCb) {\n if (argsNum < 2) {\n throw new Error('Too few arguments provided')\n }\n\n if (argsNum === 2) {\n cb = text\n text = canvas\n canvas = opts = undefined\n } else if (argsNum === 3) {\n if (canvas.getContext && typeof cb === 'undefined') {\n cb = opts\n opts = undefined\n } else {\n cb = opts\n opts = text\n text = canvas\n canvas = undefined\n }\n }\n } else {\n if (argsNum < 1) {\n throw new Error('Too few arguments provided')\n }\n\n if (argsNum === 1) {\n text = canvas\n canvas = opts = undefined\n } else if (argsNum === 2 && !canvas.getContext) {\n opts = text\n text = canvas\n canvas = undefined\n }\n\n return new Promise(function (resolve, reject) {\n try {\n const data = QRCode.create(text, opts)\n resolve(renderFunc(data, canvas, opts))\n } catch (e) {\n reject(e)\n }\n })\n }\n\n try {\n const data = QRCode.create(text, opts)\n cb(null, renderFunc(data, canvas, opts))\n } catch (e) {\n cb(e)\n }\n}\n\nexports.create = QRCode.create\nexports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)\nexports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)\n\n// only svg for now.\nexports.toString = renderCanvas.bind(null, function (data, _, opts) {\n return SvgRenderer.render(data, opts)\n})\n","// can-promise has a crash in some versions of react native that dont have\n// standard global objects\n// https://github.com/soldair/node-qrcode/issues/157\n\nmodule.exports = function () {\n return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then\n}\n","/**\n * Alignment pattern are fixed reference pattern in defined positions\n * in a matrix symbology, which enables the decode software to re-synchronise\n * the coordinate mapping of the image modules in the event of moderate amounts\n * of distortion of the image.\n *\n * Alignment patterns are present only in QR Code symbols of version 2 or larger\n * and their number depends on the symbol version.\n */\n\nconst getSymbolSize = require('./utils').getSymbolSize\n\n/**\n * Calculate the row/column coordinates of the center module of each alignment pattern\n * for the specified QR Code version.\n *\n * The alignment patterns are positioned symmetrically on either side of the diagonal\n * running from the top left corner of the symbol to the bottom right corner.\n *\n * Since positions are simmetrical only half of the coordinates are returned.\n * Each item of the array will represent in turn the x and y coordinate.\n * @see {@link getPositions}\n *\n * @param {Number} version QR Code version\n * @return {Array} Array of coordinate\n */\nexports.getRowColCoords = function getRowColCoords (version) {\n if (version === 1) return []\n\n const posCount = Math.floor(version / 7) + 2\n const size = getSymbolSize(version)\n const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2\n const positions = [size - 7] // Last coord is always (size - 7)\n\n for (let i = 1; i < posCount - 1; i++) {\n positions[i] = positions[i - 1] - intervals\n }\n\n positions.push(6) // First coord is always 6\n\n return positions.reverse()\n}\n\n/**\n * Returns an array containing the positions of each alignment pattern.\n * Each array's element represent the center point of the pattern as (x, y) coordinates\n *\n * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}\n * and filtering out the items that overlaps with finder pattern\n *\n * @example\n * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.\n * The alignment patterns, therefore, are to be centered on (row, column)\n * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).\n * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns\n * and are not therefore used for alignment patterns.\n *\n * let pos = getPositions(7)\n * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]\n *\n * @param {Number} version QR Code version\n * @return {Array} Array of coordinates\n */\nexports.getPositions = function getPositions (version) {\n const coords = []\n const pos = exports.getRowColCoords(version)\n const posLength = pos.length\n\n for (let i = 0; i < posLength; i++) {\n for (let j = 0; j < posLength; j++) {\n // Skip if position is occupied by finder patterns\n if ((i === 0 && j === 0) || // top-left\n (i === 0 && j === posLength - 1) || // bottom-left\n (i === posLength - 1 && j === 0)) { // top-right\n continue\n }\n\n coords.push([pos[i], pos[j]])\n }\n }\n\n return coords\n}\n","const Mode = require('./mode')\n\n/**\n * Array of characters available in alphanumeric mode\n *\n * As per QR Code specification, to each character\n * is assigned a value from 0 to 44 which in this case coincides\n * with the array index\n *\n * @type {Array}\n */\nconst ALPHA_NUM_CHARS = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n ' ', '$', '%', '*', '+', '-', '.', '/', ':'\n]\n\nfunction AlphanumericData (data) {\n this.mode = Mode.ALPHANUMERIC\n this.data = data\n}\n\nAlphanumericData.getBitsLength = function getBitsLength (length) {\n return 11 * Math.floor(length / 2) + 6 * (length % 2)\n}\n\nAlphanumericData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nAlphanumericData.prototype.getBitsLength = function getBitsLength () {\n return AlphanumericData.getBitsLength(this.data.length)\n}\n\nAlphanumericData.prototype.write = function write (bitBuffer) {\n let i\n\n // Input data characters are divided into groups of two characters\n // and encoded as 11-bit binary codes.\n for (i = 0; i + 2 <= this.data.length; i += 2) {\n // The character value of the first character is multiplied by 45\n let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45\n\n // The character value of the second digit is added to the product\n value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])\n\n // The sum is then stored as 11-bit binary number\n bitBuffer.put(value, 11)\n }\n\n // If the number of input data characters is not a multiple of two,\n // the character value of the final character is encoded as a 6-bit binary number.\n if (this.data.length % 2) {\n bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)\n }\n}\n\nmodule.exports = AlphanumericData\n","function BitBuffer () {\n this.buffer = []\n this.length = 0\n}\n\nBitBuffer.prototype = {\n\n get: function (index) {\n const bufIndex = Math.floor(index / 8)\n return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1\n },\n\n put: function (num, length) {\n for (let i = 0; i < length; i++) {\n this.putBit(((num >>> (length - i - 1)) & 1) === 1)\n }\n },\n\n getLengthInBits: function () {\n return this.length\n },\n\n putBit: function (bit) {\n const bufIndex = Math.floor(this.length / 8)\n if (this.buffer.length <= bufIndex) {\n this.buffer.push(0)\n }\n\n if (bit) {\n this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))\n }\n\n this.length++\n }\n}\n\nmodule.exports = BitBuffer\n","/**\n * Helper class to handle QR Code symbol modules\n *\n * @param {Number} size Symbol size\n */\nfunction BitMatrix (size) {\n if (!size || size < 1) {\n throw new Error('BitMatrix size must be defined and greater than 0')\n }\n\n this.size = size\n this.data = new Uint8Array(size * size)\n this.reservedBit = new Uint8Array(size * size)\n}\n\n/**\n * Set bit value at specified location\n * If reserved flag is set, this bit will be ignored during masking process\n *\n * @param {Number} row\n * @param {Number} col\n * @param {Boolean} value\n * @param {Boolean} reserved\n */\nBitMatrix.prototype.set = function (row, col, value, reserved) {\n const index = row * this.size + col\n this.data[index] = value\n if (reserved) this.reservedBit[index] = true\n}\n\n/**\n * Returns bit value at specified location\n *\n * @param {Number} row\n * @param {Number} col\n * @return {Boolean}\n */\nBitMatrix.prototype.get = function (row, col) {\n return this.data[row * this.size + col]\n}\n\n/**\n * Applies xor operator at specified location\n * (used during masking process)\n *\n * @param {Number} row\n * @param {Number} col\n * @param {Boolean} value\n */\nBitMatrix.prototype.xor = function (row, col, value) {\n this.data[row * this.size + col] ^= value\n}\n\n/**\n * Check if bit at specified location is reserved\n *\n * @param {Number} row\n * @param {Number} col\n * @return {Boolean}\n */\nBitMatrix.prototype.isReserved = function (row, col) {\n return this.reservedBit[row * this.size + col]\n}\n\nmodule.exports = BitMatrix\n","const encodeUtf8 = require('encode-utf8')\nconst Mode = require('./mode')\n\nfunction ByteData (data) {\n this.mode = Mode.BYTE\n this.data = new Uint8Array(encodeUtf8(data))\n}\n\nByteData.getBitsLength = function getBitsLength (length) {\n return length * 8\n}\n\nByteData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nByteData.prototype.getBitsLength = function getBitsLength () {\n return ByteData.getBitsLength(this.data.length)\n}\n\nByteData.prototype.write = function (bitBuffer) {\n for (let i = 0, l = this.data.length; i < l; i++) {\n bitBuffer.put(this.data[i], 8)\n }\n}\n\nmodule.exports = ByteData\n","const ECLevel = require('./error-correction-level')\r\n\r\nconst EC_BLOCKS_TABLE = [\r\n// L M Q H\r\n 1, 1, 1, 1,\r\n 1, 1, 1, 1,\r\n 1, 1, 2, 2,\r\n 1, 2, 2, 4,\r\n 1, 2, 4, 4,\r\n 2, 4, 4, 4,\r\n 2, 4, 6, 5,\r\n 2, 4, 6, 6,\r\n 2, 5, 8, 8,\r\n 4, 5, 8, 8,\r\n 4, 5, 8, 11,\r\n 4, 8, 10, 11,\r\n 4, 9, 12, 16,\r\n 4, 9, 16, 16,\r\n 6, 10, 12, 18,\r\n 6, 10, 17, 16,\r\n 6, 11, 16, 19,\r\n 6, 13, 18, 21,\r\n 7, 14, 21, 25,\r\n 8, 16, 20, 25,\r\n 8, 17, 23, 25,\r\n 9, 17, 23, 34,\r\n 9, 18, 25, 30,\r\n 10, 20, 27, 32,\r\n 12, 21, 29, 35,\r\n 12, 23, 34, 37,\r\n 12, 25, 34, 40,\r\n 13, 26, 35, 42,\r\n 14, 28, 38, 45,\r\n 15, 29, 40, 48,\r\n 16, 31, 43, 51,\r\n 17, 33, 45, 54,\r\n 18, 35, 48, 57,\r\n 19, 37, 51, 60,\r\n 19, 38, 53, 63,\r\n 20, 40, 56, 66,\r\n 21, 43, 59, 70,\r\n 22, 45, 62, 74,\r\n 24, 47, 65, 77,\r\n 25, 49, 68, 81\r\n]\r\n\r\nconst EC_CODEWORDS_TABLE = [\r\n// L M Q H\r\n 7, 10, 13, 17,\r\n 10, 16, 22, 28,\r\n 15, 26, 36, 44,\r\n 20, 36, 52, 64,\r\n 26, 48, 72, 88,\r\n 36, 64, 96, 112,\r\n 40, 72, 108, 130,\r\n 48, 88, 132, 156,\r\n 60, 110, 160, 192,\r\n 72, 130, 192, 224,\r\n 80, 150, 224, 264,\r\n 96, 176, 260, 308,\r\n 104, 198, 288, 352,\r\n 120, 216, 320, 384,\r\n 132, 240, 360, 432,\r\n 144, 280, 408, 480,\r\n 168, 308, 448, 532,\r\n 180, 338, 504, 588,\r\n 196, 364, 546, 650,\r\n 224, 416, 600, 700,\r\n 224, 442, 644, 750,\r\n 252, 476, 690, 816,\r\n 270, 504, 750, 900,\r\n 300, 560, 810, 960,\r\n 312, 588, 870, 1050,\r\n 336, 644, 952, 1110,\r\n 360, 700, 1020, 1200,\r\n 390, 728, 1050, 1260,\r\n 420, 784, 1140, 1350,\r\n 450, 812, 1200, 1440,\r\n 480, 868, 1290, 1530,\r\n 510, 924, 1350, 1620,\r\n 540, 980, 1440, 1710,\r\n 570, 1036, 1530, 1800,\r\n 570, 1064, 1590, 1890,\r\n 600, 1120, 1680, 1980,\r\n 630, 1204, 1770, 2100,\r\n 660, 1260, 1860, 2220,\r\n 720, 1316, 1950, 2310,\r\n 750, 1372, 2040, 2430\r\n]\r\n\r\n/**\r\n * Returns the number of error correction block that the QR Code should contain\r\n * for the specified version and error correction level.\r\n *\r\n * @param {Number} version QR Code version\r\n * @param {Number} errorCorrectionLevel Error correction level\r\n * @return {Number} Number of error correction blocks\r\n */\r\nexports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {\r\n switch (errorCorrectionLevel) {\r\n case ECLevel.L:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]\r\n case ECLevel.M:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]\r\n case ECLevel.Q:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]\r\n case ECLevel.H:\r\n return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]\r\n default:\r\n return undefined\r\n }\r\n}\r\n\r\n/**\r\n * Returns the number of error correction codewords to use for the specified\r\n * version and error correction level.\r\n *\r\n * @param {Number} version QR Code version\r\n * @param {Number} errorCorrectionLevel Error correction level\r\n * @return {Number} Number of error correction codewords\r\n */\r\nexports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {\r\n switch (errorCorrectionLevel) {\r\n case ECLevel.L:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]\r\n case ECLevel.M:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]\r\n case ECLevel.Q:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]\r\n case ECLevel.H:\r\n return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]\r\n default:\r\n return undefined\r\n }\r\n}\r\n","exports.L = { bit: 1 }\nexports.M = { bit: 0 }\nexports.Q = { bit: 3 }\nexports.H = { bit: 2 }\n\nfunction fromString (string) {\n if (typeof string !== 'string') {\n throw new Error('Param is not a string')\n }\n\n const lcStr = string.toLowerCase()\n\n switch (lcStr) {\n case 'l':\n case 'low':\n return exports.L\n\n case 'm':\n case 'medium':\n return exports.M\n\n case 'q':\n case 'quartile':\n return exports.Q\n\n case 'h':\n case 'high':\n return exports.H\n\n default:\n throw new Error('Unknown EC Level: ' + string)\n }\n}\n\nexports.isValid = function isValid (level) {\n return level && typeof level.bit !== 'undefined' &&\n level.bit >= 0 && level.bit < 4\n}\n\nexports.from = function from (value, defaultValue) {\n if (exports.isValid(value)) {\n return value\n }\n\n try {\n return fromString(value)\n } catch (e) {\n return defaultValue\n }\n}\n","const getSymbolSize = require('./utils').getSymbolSize\nconst FINDER_PATTERN_SIZE = 7\n\n/**\n * Returns an array containing the positions of each finder pattern.\n * Each array's element represent the top-left point of the pattern as (x, y) coordinates\n *\n * @param {Number} version QR Code version\n * @return {Array} Array of coordinates\n */\nexports.getPositions = function getPositions (version) {\n const size = getSymbolSize(version)\n\n return [\n // top-left\n [0, 0],\n // top-right\n [size - FINDER_PATTERN_SIZE, 0],\n // bottom-left\n [0, size - FINDER_PATTERN_SIZE]\n ]\n}\n","const Utils = require('./utils')\n\nconst G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)\nconst G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)\nconst G15_BCH = Utils.getBCHDigit(G15)\n\n/**\n * Returns format information with relative error correction bits\n *\n * The format information is a 15-bit sequence containing 5 data bits,\n * with 10 error correction bits calculated using the (15, 5) BCH code.\n *\n * @param {Number} errorCorrectionLevel Error correction level\n * @param {Number} mask Mask pattern\n * @return {Number} Encoded format information bits\n */\nexports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {\n const data = ((errorCorrectionLevel.bit << 3) | mask)\n let d = data << 10\n\n while (Utils.getBCHDigit(d) - G15_BCH >= 0) {\n d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))\n }\n\n // xor final data with mask pattern in order to ensure that\n // no combination of Error Correction Level and data mask pattern\n // will result in an all-zero data string\n return ((data << 10) | d) ^ G15_MASK\n}\n","const EXP_TABLE = new Uint8Array(512)\nconst LOG_TABLE = new Uint8Array(256)\n/**\n * Precompute the log and anti-log tables for faster computation later\n *\n * For each possible value in the galois field 2^8, we will pre-compute\n * the logarithm and anti-logarithm (exponential) of this value\n *\n * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}\n */\n;(function initTables () {\n let x = 1\n for (let i = 0; i < 255; i++) {\n EXP_TABLE[i] = x\n LOG_TABLE[x] = i\n\n x <<= 1 // multiply by 2\n\n // The QR code specification says to use byte-wise modulo 100011101 arithmetic.\n // This means that when a number is 256 or larger, it should be XORed with 0x11D.\n if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)\n x ^= 0x11D\n }\n }\n\n // Optimization: double the size of the anti-log table so that we don't need to mod 255 to\n // stay inside the bounds (because we will mainly use this table for the multiplication of\n // two GF numbers, no more).\n // @see {@link mul}\n for (let i = 255; i < 512; i++) {\n EXP_TABLE[i] = EXP_TABLE[i - 255]\n }\n}())\n\n/**\n * Returns log value of n inside Galois Field\n *\n * @param {Number} n\n * @return {Number}\n */\nexports.log = function log (n) {\n if (n < 1) throw new Error('log(' + n + ')')\n return LOG_TABLE[n]\n}\n\n/**\n * Returns anti-log value of n inside Galois Field\n *\n * @param {Number} n\n * @return {Number}\n */\nexports.exp = function exp (n) {\n return EXP_TABLE[n]\n}\n\n/**\n * Multiplies two number inside Galois Field\n *\n * @param {Number} x\n * @param {Number} y\n * @return {Number}\n */\nexports.mul = function mul (x, y) {\n if (x === 0 || y === 0) return 0\n\n // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized\n // @see {@link initTables}\n return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]\n}\n","const Mode = require('./mode')\nconst Utils = require('./utils')\n\nfunction KanjiData (data) {\n this.mode = Mode.KANJI\n this.data = data\n}\n\nKanjiData.getBitsLength = function getBitsLength (length) {\n return length * 13\n}\n\nKanjiData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nKanjiData.prototype.getBitsLength = function getBitsLength () {\n return KanjiData.getBitsLength(this.data.length)\n}\n\nKanjiData.prototype.write = function (bitBuffer) {\n let i\n\n // In the Shift JIS system, Kanji characters are represented by a two byte combination.\n // These byte values are shifted from the JIS X 0208 values.\n // JIS X 0208 gives details of the shift coded representation.\n for (i = 0; i < this.data.length; i++) {\n let value = Utils.toSJIS(this.data[i])\n\n // For characters with Shift JIS values from 0x8140 to 0x9FFC:\n if (value >= 0x8140 && value <= 0x9FFC) {\n // Subtract 0x8140 from Shift JIS value\n value -= 0x8140\n\n // For characters with Shift JIS values from 0xE040 to 0xEBBF\n } else if (value >= 0xE040 && value <= 0xEBBF) {\n // Subtract 0xC140 from Shift JIS value\n value -= 0xC140\n } else {\n throw new Error(\n 'Invalid SJIS character: ' + this.data[i] + '\\n' +\n 'Make sure your charset is UTF-8')\n }\n\n // Multiply most significant byte of result by 0xC0\n // and add least significant byte to product\n value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)\n\n // Convert result to a 13-bit binary string\n bitBuffer.put(value, 13)\n }\n}\n\nmodule.exports = KanjiData\n","/**\n * Data mask pattern reference\n * @type {Object}\n */\nexports.Patterns = {\n PATTERN000: 0,\n PATTERN001: 1,\n PATTERN010: 2,\n PATTERN011: 3,\n PATTERN100: 4,\n PATTERN101: 5,\n PATTERN110: 6,\n PATTERN111: 7\n}\n\n/**\n * Weighted penalty scores for the undesirable features\n * @type {Object}\n */\nconst PenaltyScores = {\n N1: 3,\n N2: 3,\n N3: 40,\n N4: 10\n}\n\n/**\n * Check if mask pattern value is valid\n *\n * @param {Number} mask Mask pattern\n * @return {Boolean} true if valid, false otherwise\n */\nexports.isValid = function isValid (mask) {\n return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7\n}\n\n/**\n * Returns mask pattern from a value.\n * If value is not valid, returns undefined\n *\n * @param {Number|String} value Mask pattern value\n * @return {Number} Valid mask pattern or undefined\n */\nexports.from = function from (value) {\n return exports.isValid(value) ? parseInt(value, 10) : undefined\n}\n\n/**\n* Find adjacent modules in row/column with the same color\n* and assign a penalty value.\n*\n* Points: N1 + i\n* i is the amount by which the number of adjacent modules of the same color exceeds 5\n*/\nexports.getPenaltyN1 = function getPenaltyN1 (data) {\n const size = data.size\n let points = 0\n let sameCountCol = 0\n let sameCountRow = 0\n let lastCol = null\n let lastRow = null\n\n for (let row = 0; row < size; row++) {\n sameCountCol = sameCountRow = 0\n lastCol = lastRow = null\n\n for (let col = 0; col < size; col++) {\n let module = data.get(row, col)\n if (module === lastCol) {\n sameCountCol++\n } else {\n if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)\n lastCol = module\n sameCountCol = 1\n }\n\n module = data.get(col, row)\n if (module === lastRow) {\n sameCountRow++\n } else {\n if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)\n lastRow = module\n sameCountRow = 1\n }\n }\n\n if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)\n if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)\n }\n\n return points\n}\n\n/**\n * Find 2x2 blocks with the same color and assign a penalty value\n *\n * Points: N2 * (m - 1) * (n - 1)\n */\nexports.getPenaltyN2 = function getPenaltyN2 (data) {\n const size = data.size\n let points = 0\n\n for (let row = 0; row < size - 1; row++) {\n for (let col = 0; col < size - 1; col++) {\n const last = data.get(row, col) +\n data.get(row, col + 1) +\n data.get(row + 1, col) +\n data.get(row + 1, col + 1)\n\n if (last === 4 || last === 0) points++\n }\n }\n\n return points * PenaltyScores.N2\n}\n\n/**\n * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,\n * preceded or followed by light area 4 modules wide\n *\n * Points: N3 * number of pattern found\n */\nexports.getPenaltyN3 = function getPenaltyN3 (data) {\n const size = data.size\n let points = 0\n let bitsCol = 0\n let bitsRow = 0\n\n for (let row = 0; row < size; row++) {\n bitsCol = bitsRow = 0\n for (let col = 0; col < size; col++) {\n bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)\n if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++\n\n bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)\n if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++\n }\n }\n\n return points * PenaltyScores.N3\n}\n\n/**\n * Calculate proportion of dark modules in entire symbol\n *\n * Points: N4 * k\n *\n * k is the rating of the deviation of the proportion of dark modules\n * in the symbol from 50% in steps of 5%\n */\nexports.getPenaltyN4 = function getPenaltyN4 (data) {\n let darkCount = 0\n const modulesCount = data.data.length\n\n for (let i = 0; i < modulesCount; i++) darkCount += data.data[i]\n\n const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)\n\n return k * PenaltyScores.N4\n}\n\n/**\n * Return mask value at given position\n *\n * @param {Number} maskPattern Pattern reference value\n * @param {Number} i Row\n * @param {Number} j Column\n * @return {Boolean} Mask value\n */\nfunction getMaskAt (maskPattern, i, j) {\n switch (maskPattern) {\n case exports.Patterns.PATTERN000: return (i + j) % 2 === 0\n case exports.Patterns.PATTERN001: return i % 2 === 0\n case exports.Patterns.PATTERN010: return j % 3 === 0\n case exports.Patterns.PATTERN011: return (i + j) % 3 === 0\n case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0\n case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0\n case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0\n case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0\n\n default: throw new Error('bad maskPattern:' + maskPattern)\n }\n}\n\n/**\n * Apply a mask pattern to a BitMatrix\n *\n * @param {Number} pattern Pattern reference number\n * @param {BitMatrix} data BitMatrix data\n */\nexports.applyMask = function applyMask (pattern, data) {\n const size = data.size\n\n for (let col = 0; col < size; col++) {\n for (let row = 0; row < size; row++) {\n if (data.isReserved(row, col)) continue\n data.xor(row, col, getMaskAt(pattern, row, col))\n }\n }\n}\n\n/**\n * Returns the best mask pattern for data\n *\n * @param {BitMatrix} data\n * @return {Number} Mask pattern reference number\n */\nexports.getBestMask = function getBestMask (data, setupFormatFunc) {\n const numPatterns = Object.keys(exports.Patterns).length\n let bestPattern = 0\n let lowerPenalty = Infinity\n\n for (let p = 0; p < numPatterns; p++) {\n setupFormatFunc(p)\n exports.applyMask(p, data)\n\n // Calculate penalty\n const penalty =\n exports.getPenaltyN1(data) +\n exports.getPenaltyN2(data) +\n exports.getPenaltyN3(data) +\n exports.getPenaltyN4(data)\n\n // Undo previously applied mask\n exports.applyMask(p, data)\n\n if (penalty < lowerPenalty) {\n lowerPenalty = penalty\n bestPattern = p\n }\n }\n\n return bestPattern\n}\n","const VersionCheck = require('./version-check')\nconst Regex = require('./regex')\n\n/**\n * Numeric mode encodes data from the decimal digit set (0 - 9)\n * (byte values 30HEX to 39HEX).\n * Normally, 3 data characters are represented by 10 bits.\n *\n * @type {Object}\n */\nexports.NUMERIC = {\n id: 'Numeric',\n bit: 1 << 0,\n ccBits: [10, 12, 14]\n}\n\n/**\n * Alphanumeric mode encodes data from a set of 45 characters,\n * i.e. 10 numeric digits (0 - 9),\n * 26 alphabetic characters (A - Z),\n * and 9 symbols (SP, $, %, *, +, -, ., /, :).\n * Normally, two input characters are represented by 11 bits.\n *\n * @type {Object}\n */\nexports.ALPHANUMERIC = {\n id: 'Alphanumeric',\n bit: 1 << 1,\n ccBits: [9, 11, 13]\n}\n\n/**\n * In byte mode, data is encoded at 8 bits per character.\n *\n * @type {Object}\n */\nexports.BYTE = {\n id: 'Byte',\n bit: 1 << 2,\n ccBits: [8, 16, 16]\n}\n\n/**\n * The Kanji mode efficiently encodes Kanji characters in accordance with\n * the Shift JIS system based on JIS X 0208.\n * The Shift JIS values are shifted from the JIS X 0208 values.\n * JIS X 0208 gives details of the shift coded representation.\n * Each two-byte character value is compacted to a 13-bit binary codeword.\n *\n * @type {Object}\n */\nexports.KANJI = {\n id: 'Kanji',\n bit: 1 << 3,\n ccBits: [8, 10, 12]\n}\n\n/**\n * Mixed mode will contain a sequences of data in a combination of any of\n * the modes described above\n *\n * @type {Object}\n */\nexports.MIXED = {\n bit: -1\n}\n\n/**\n * Returns the number of bits needed to store the data length\n * according to QR Code specifications.\n *\n * @param {Mode} mode Data mode\n * @param {Number} version QR Code version\n * @return {Number} Number of bits\n */\nexports.getCharCountIndicator = function getCharCountIndicator (mode, version) {\n if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)\n\n if (!VersionCheck.isValid(version)) {\n throw new Error('Invalid version: ' + version)\n }\n\n if (version >= 1 && version < 10) return mode.ccBits[0]\n else if (version < 27) return mode.ccBits[1]\n return mode.ccBits[2]\n}\n\n/**\n * Returns the most efficient mode to store the specified data\n *\n * @param {String} dataStr Input data string\n * @return {Mode} Best mode\n */\nexports.getBestModeForData = function getBestModeForData (dataStr) {\n if (Regex.testNumeric(dataStr)) return exports.NUMERIC\n else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC\n else if (Regex.testKanji(dataStr)) return exports.KANJI\n else return exports.BYTE\n}\n\n/**\n * Return mode name as string\n *\n * @param {Mode} mode Mode object\n * @returns {String} Mode name\n */\nexports.toString = function toString (mode) {\n if (mode && mode.id) return mode.id\n throw new Error('Invalid mode')\n}\n\n/**\n * Check if input param is a valid mode object\n *\n * @param {Mode} mode Mode object\n * @returns {Boolean} True if valid mode, false otherwise\n */\nexports.isValid = function isValid (mode) {\n return mode && mode.bit && mode.ccBits\n}\n\n/**\n * Get mode object from its name\n *\n * @param {String} string Mode name\n * @returns {Mode} Mode object\n */\nfunction fromString (string) {\n if (typeof string !== 'string') {\n throw new Error('Param is not a string')\n }\n\n const lcStr = string.toLowerCase()\n\n switch (lcStr) {\n case 'numeric':\n return exports.NUMERIC\n case 'alphanumeric':\n return exports.ALPHANUMERIC\n case 'kanji':\n return exports.KANJI\n case 'byte':\n return exports.BYTE\n default:\n throw new Error('Unknown mode: ' + string)\n }\n}\n\n/**\n * Returns mode from a value.\n * If value is not a valid mode, returns defaultValue\n *\n * @param {Mode|String} value Encoding mode\n * @param {Mode} defaultValue Fallback value\n * @return {Mode} Encoding mode\n */\nexports.from = function from (value, defaultValue) {\n if (exports.isValid(value)) {\n return value\n }\n\n try {\n return fromString(value)\n } catch (e) {\n return defaultValue\n }\n}\n","const Mode = require('./mode')\n\nfunction NumericData (data) {\n this.mode = Mode.NUMERIC\n this.data = data.toString()\n}\n\nNumericData.getBitsLength = function getBitsLength (length) {\n return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)\n}\n\nNumericData.prototype.getLength = function getLength () {\n return this.data.length\n}\n\nNumericData.prototype.getBitsLength = function getBitsLength () {\n return NumericData.getBitsLength(this.data.length)\n}\n\nNumericData.prototype.write = function write (bitBuffer) {\n let i, group, value\n\n // The input data string is divided into groups of three digits,\n // and each group is converted to its 10-bit binary equivalent.\n for (i = 0; i + 3 <= this.data.length; i += 3) {\n group = this.data.substr(i, 3)\n value = parseInt(group, 10)\n\n bitBuffer.put(value, 10)\n }\n\n // If the number of input digits is not an exact multiple of three,\n // the final one or two digits are converted to 4 or 7 bits respectively.\n const remainingNum = this.data.length - i\n if (remainingNum > 0) {\n group = this.data.substr(i)\n value = parseInt(group, 10)\n\n bitBuffer.put(value, remainingNum * 3 + 1)\n }\n}\n\nmodule.exports = NumericData\n","const GF = require('./galois-field')\n\n/**\n * Multiplies two polynomials inside Galois Field\n *\n * @param {Uint8Array} p1 Polynomial\n * @param {Uint8Array} p2 Polynomial\n * @return {Uint8Array} Product of p1 and p2\n */\nexports.mul = function mul (p1, p2) {\n const coeff = new Uint8Array(p1.length + p2.length - 1)\n\n for (let i = 0; i < p1.length; i++) {\n for (let j = 0; j < p2.length; j++) {\n coeff[i + j] ^= GF.mul(p1[i], p2[j])\n }\n }\n\n return coeff\n}\n\n/**\n * Calculate the remainder of polynomials division\n *\n * @param {Uint8Array} divident Polynomial\n * @param {Uint8Array} divisor Polynomial\n * @return {Uint8Array} Remainder\n */\nexports.mod = function mod (divident, divisor) {\n let result = new Uint8Array(divident)\n\n while ((result.length - divisor.length) >= 0) {\n const coeff = result[0]\n\n for (let i = 0; i < divisor.length; i++) {\n result[i] ^= GF.mul(divisor[i], coeff)\n }\n\n // remove all zeros from buffer head\n let offset = 0\n while (offset < result.length && result[offset] === 0) offset++\n result = result.slice(offset)\n }\n\n return result\n}\n\n/**\n * Generate an irreducible generator polynomial of specified degree\n * (used by Reed-Solomon encoder)\n *\n * @param {Number} degree Degree of the generator polynomial\n * @return {Uint8Array} Buffer containing polynomial coefficients\n */\nexports.generateECPolynomial = function generateECPolynomial (degree) {\n let poly = new Uint8Array([1])\n for (let i = 0; i < degree; i++) {\n poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]))\n }\n\n return poly\n}\n","const Utils = require('./utils')\nconst ECLevel = require('./error-correction-level')\nconst BitBuffer = require('./bit-buffer')\nconst BitMatrix = require('./bit-matrix')\nconst AlignmentPattern = require('./alignment-pattern')\nconst FinderPattern = require('./finder-pattern')\nconst MaskPattern = require('./mask-pattern')\nconst ECCode = require('./error-correction-code')\nconst ReedSolomonEncoder = require('./reed-solomon-encoder')\nconst Version = require('./version')\nconst FormatInfo = require('./format-info')\nconst Mode = require('./mode')\nconst Segments = require('./segments')\n\n/**\n * QRCode for JavaScript\n *\n * modified by Ryan Day for nodejs support\n * Copyright (c) 2011 Ryan Day\n *\n * Licensed under the MIT license:\n * http://www.opensource.org/licenses/mit-license.php\n *\n//---------------------------------------------------------------------\n// QRCode for JavaScript\n//\n// Copyright (c) 2009 Kazuhiko Arase\n//\n// URL: http://www.d-project.com/\n//\n// Licensed under the MIT license:\n// http://www.opensource.org/licenses/mit-license.php\n//\n// The word \"QR Code\" is registered trademark of\n// DENSO WAVE INCORPORATED\n// http://www.denso-wave.com/qrcode/faqpatent-e.html\n//\n//---------------------------------------------------------------------\n*/\n\n/**\n * Add finder patterns bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Number} version QR Code version\n */\nfunction setupFinderPattern (matrix, version) {\n const size = matrix.size\n const pos = FinderPattern.getPositions(version)\n\n for (let i = 0; i < pos.length; i++) {\n const row = pos[i][0]\n const col = pos[i][1]\n\n for (let r = -1; r <= 7; r++) {\n if (row + r <= -1 || size <= row + r) continue\n\n for (let c = -1; c <= 7; c++) {\n if (col + c <= -1 || size <= col + c) continue\n\n if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||\n (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||\n (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {\n matrix.set(row + r, col + c, true, true)\n } else {\n matrix.set(row + r, col + c, false, true)\n }\n }\n }\n }\n}\n\n/**\n * Add timing pattern bits to matrix\n *\n * Note: this function must be called before {@link setupAlignmentPattern}\n *\n * @param {BitMatrix} matrix Modules matrix\n */\nfunction setupTimingPattern (matrix) {\n const size = matrix.size\n\n for (let r = 8; r < size - 8; r++) {\n const value = r % 2 === 0\n matrix.set(r, 6, value, true)\n matrix.set(6, r, value, true)\n }\n}\n\n/**\n * Add alignment patterns bits to matrix\n *\n * Note: this function must be called after {@link setupTimingPattern}\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Number} version QR Code version\n */\nfunction setupAlignmentPattern (matrix, version) {\n const pos = AlignmentPattern.getPositions(version)\n\n for (let i = 0; i < pos.length; i++) {\n const row = pos[i][0]\n const col = pos[i][1]\n\n for (let r = -2; r <= 2; r++) {\n for (let c = -2; c <= 2; c++) {\n if (r === -2 || r === 2 || c === -2 || c === 2 ||\n (r === 0 && c === 0)) {\n matrix.set(row + r, col + c, true, true)\n } else {\n matrix.set(row + r, col + c, false, true)\n }\n }\n }\n }\n}\n\n/**\n * Add version info bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Number} version QR Code version\n */\nfunction setupVersionInfo (matrix, version) {\n const size = matrix.size\n const bits = Version.getEncodedBits(version)\n let row, col, mod\n\n for (let i = 0; i < 18; i++) {\n row = Math.floor(i / 3)\n col = i % 3 + size - 8 - 3\n mod = ((bits >> i) & 1) === 1\n\n matrix.set(row, col, mod, true)\n matrix.set(col, row, mod, true)\n }\n}\n\n/**\n * Add format info bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @param {Number} maskPattern Mask pattern reference value\n */\nfunction setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {\n const size = matrix.size\n const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)\n let i, mod\n\n for (i = 0; i < 15; i++) {\n mod = ((bits >> i) & 1) === 1\n\n // vertical\n if (i < 6) {\n matrix.set(i, 8, mod, true)\n } else if (i < 8) {\n matrix.set(i + 1, 8, mod, true)\n } else {\n matrix.set(size - 15 + i, 8, mod, true)\n }\n\n // horizontal\n if (i < 8) {\n matrix.set(8, size - i - 1, mod, true)\n } else if (i < 9) {\n matrix.set(8, 15 - i - 1 + 1, mod, true)\n } else {\n matrix.set(8, 15 - i - 1, mod, true)\n }\n }\n\n // fixed module\n matrix.set(size - 8, 8, 1, true)\n}\n\n/**\n * Add encoded data bits to matrix\n *\n * @param {BitMatrix} matrix Modules matrix\n * @param {Uint8Array} data Data codewords\n */\nfunction setupData (matrix, data) {\n const size = matrix.size\n let inc = -1\n let row = size - 1\n let bitIndex = 7\n let byteIndex = 0\n\n for (let col = size - 1; col > 0; col -= 2) {\n if (col === 6) col--\n\n while (true) {\n for (let c = 0; c < 2; c++) {\n if (!matrix.isReserved(row, col - c)) {\n let dark = false\n\n if (byteIndex < data.length) {\n dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)\n }\n\n matrix.set(row, col - c, dark)\n bitIndex--\n\n if (bitIndex === -1) {\n byteIndex++\n bitIndex = 7\n }\n }\n }\n\n row += inc\n\n if (row < 0 || size <= row) {\n row -= inc\n inc = -inc\n break\n }\n }\n }\n}\n\n/**\n * Create encoded codewords from data input\n *\n * @param {Number} version QR Code version\n * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @param {ByteData} data Data input\n * @return {Uint8Array} Buffer containing encoded codewords\n */\nfunction createData (version, errorCorrectionLevel, segments) {\n // Prepare data buffer\n const buffer = new BitBuffer()\n\n segments.forEach(function (data) {\n // prefix data with mode indicator (4 bits)\n buffer.put(data.mode.bit, 4)\n\n // Prefix data with character count indicator.\n // The character count indicator is a string of bits that represents the\n // number of characters that are being encoded.\n // The character count indicator must be placed after the mode indicator\n // and must be a certain number of bits long, depending on the QR version\n // and data mode\n // @see {@link Mode.getCharCountIndicator}.\n buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))\n\n // add binary data sequence to buffer\n data.write(buffer)\n })\n\n // Calculate required number of bits\n const totalCodewords = Utils.getSymbolTotalCodewords(version)\n const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8\n\n // Add a terminator.\n // If the bit string is shorter than the total number of required bits,\n // a terminator of up to four 0s must be added to the right side of the string.\n // If the bit string is more than four bits shorter than the required number of bits,\n // add four 0s to the end.\n if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {\n buffer.put(0, 4)\n }\n\n // If the bit string is fewer than four bits shorter, add only the number of 0s that\n // are needed to reach the required number of bits.\n\n // After adding the terminator, if the number of bits in the string is not a multiple of 8,\n // pad the string on the right with 0s to make the string's length a multiple of 8.\n while (buffer.getLengthInBits() % 8 !== 0) {\n buffer.putBit(0)\n }\n\n // Add pad bytes if the string is still shorter than the total number of required bits.\n // Extend the buffer to fill the data capacity of the symbol corresponding to\n // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)\n // and 00010001 (0x11) alternately.\n const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8\n for (let i = 0; i < remainingByte; i++) {\n buffer.put(i % 2 ? 0x11 : 0xEC, 8)\n }\n\n return createCodewords(buffer, version, errorCorrectionLevel)\n}\n\n/**\n * Encode input data with Reed-Solomon and return codewords with\n * relative error correction bits\n *\n * @param {BitBuffer} bitBuffer Data to encode\n * @param {Number} version QR Code version\n * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @return {Uint8Array} Buffer containing encoded codewords\n */\nfunction createCodewords (bitBuffer, version, errorCorrectionLevel) {\n // Total codewords for this QR code version (Data + Error correction)\n const totalCodewords = Utils.getSymbolTotalCodewords(version)\n\n // Total number of error correction codewords\n const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n\n // Total number of data codewords\n const dataTotalCodewords = totalCodewords - ecTotalCodewords\n\n // Total number of blocks\n const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)\n\n // Calculate how many blocks each group should contain\n const blocksInGroup2 = totalCodewords % ecTotalBlocks\n const blocksInGroup1 = ecTotalBlocks - blocksInGroup2\n\n const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)\n\n const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)\n const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1\n\n // Number of EC codewords is the same for both groups\n const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1\n\n // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount\n const rs = new ReedSolomonEncoder(ecCount)\n\n let offset = 0\n const dcData = new Array(ecTotalBlocks)\n const ecData = new Array(ecTotalBlocks)\n let maxDataSize = 0\n const buffer = new Uint8Array(bitBuffer.buffer)\n\n // Divide the buffer into the required number of blocks\n for (let b = 0; b < ecTotalBlocks; b++) {\n const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2\n\n // extract a block of data from buffer\n dcData[b] = buffer.slice(offset, offset + dataSize)\n\n // Calculate EC codewords for this data block\n ecData[b] = rs.encode(dcData[b])\n\n offset += dataSize\n maxDataSize = Math.max(maxDataSize, dataSize)\n }\n\n // Create final data\n // Interleave the data and error correction codewords from each block\n const data = new Uint8Array(totalCodewords)\n let index = 0\n let i, r\n\n // Add data codewords\n for (i = 0; i < maxDataSize; i++) {\n for (r = 0; r < ecTotalBlocks; r++) {\n if (i < dcData[r].length) {\n data[index++] = dcData[r][i]\n }\n }\n }\n\n // Apped EC codewords\n for (i = 0; i < ecCount; i++) {\n for (r = 0; r < ecTotalBlocks; r++) {\n data[index++] = ecData[r][i]\n }\n }\n\n return data\n}\n\n/**\n * Build QR Code symbol\n *\n * @param {String} data Input string\n * @param {Number} version QR Code version\n * @param {ErrorCorretionLevel} errorCorrectionLevel Error level\n * @param {MaskPattern} maskPattern Mask pattern\n * @return {Object} Object containing symbol data\n */\nfunction createSymbol (data, version, errorCorrectionLevel, maskPattern) {\n let segments\n\n if (Array.isArray(data)) {\n segments = Segments.fromArray(data)\n } else if (typeof data === 'string') {\n let estimatedVersion = version\n\n if (!estimatedVersion) {\n const rawSegments = Segments.rawSplit(data)\n\n // Estimate best version that can contain raw splitted segments\n estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel)\n }\n\n // Build optimized segments\n // If estimated version is undefined, try with the highest version\n segments = Segments.fromString(data, estimatedVersion || 40)\n } else {\n throw new Error('Invalid data')\n }\n\n // Get the min version that can contain data\n const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel)\n\n // If no version is found, data cannot be stored\n if (!bestVersion) {\n throw new Error('The amount of data is too big to be stored in a QR Code')\n }\n\n // If not specified, use min version as default\n if (!version) {\n version = bestVersion\n\n // Check if the specified version can contain the data\n } else if (version < bestVersion) {\n throw new Error('\\n' +\n 'The chosen QR Code version cannot contain this amount of data.\\n' +\n 'Minimum version required to store current data is: ' + bestVersion + '.\\n'\n )\n }\n\n const dataBits = createData(version, errorCorrectionLevel, segments)\n\n // Allocate matrix buffer\n const moduleCount = Utils.getSymbolSize(version)\n const modules = new BitMatrix(moduleCount)\n\n // Add function modules\n setupFinderPattern(modules, version)\n setupTimingPattern(modules)\n setupAlignmentPattern(modules, version)\n\n // Add temporary dummy bits for format info just to set them as reserved.\n // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}\n // since the masking operation must be performed only on the encoding region.\n // These blocks will be replaced with correct values later in code.\n setupFormatInfo(modules, errorCorrectionLevel, 0)\n\n if (version >= 7) {\n setupVersionInfo(modules, version)\n }\n\n // Add data codewords\n setupData(modules, dataBits)\n\n if (isNaN(maskPattern)) {\n // Find best mask pattern\n maskPattern = MaskPattern.getBestMask(modules,\n setupFormatInfo.bind(null, modules, errorCorrectionLevel))\n }\n\n // Apply mask pattern\n MaskPattern.applyMask(maskPattern, modules)\n\n // Replace format info bits with correct values\n setupFormatInfo(modules, errorCorrectionLevel, maskPattern)\n\n return {\n modules: modules,\n version: version,\n errorCorrectionLevel: errorCorrectionLevel,\n maskPattern: maskPattern,\n segments: segments\n }\n}\n\n/**\n * QR Code\n *\n * @param {String | Array} data Input data\n * @param {Object} options Optional configurations\n * @param {Number} options.version QR Code version\n * @param {String} options.errorCorrectionLevel Error correction level\n * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis\n */\nexports.create = function create (data, options) {\n if (typeof data === 'undefined' || data === '') {\n throw new Error('No input text')\n }\n\n let errorCorrectionLevel = ECLevel.M\n let version\n let mask\n\n if (typeof options !== 'undefined') {\n // Use higher error correction level as default\n errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)\n version = Version.from(options.version)\n mask = MaskPattern.from(options.maskPattern)\n\n if (options.toSJISFunc) {\n Utils.setToSJISFunction(options.toSJISFunc)\n }\n }\n\n return createSymbol(data, version, errorCorrectionLevel, mask)\n}\n","const Polynomial = require('./polynomial')\n\nfunction ReedSolomonEncoder (degree) {\n this.genPoly = undefined\n this.degree = degree\n\n if (this.degree) this.initialize(this.degree)\n}\n\n/**\n * Initialize the encoder.\n * The input param should correspond to the number of error correction codewords.\n *\n * @param {Number} degree\n */\nReedSolomonEncoder.prototype.initialize = function initialize (degree) {\n // create an irreducible generator polynomial\n this.degree = degree\n this.genPoly = Polynomial.generateECPolynomial(this.degree)\n}\n\n/**\n * Encodes a chunk of data\n *\n * @param {Uint8Array} data Buffer containing input data\n * @return {Uint8Array} Buffer containing encoded data\n */\nReedSolomonEncoder.prototype.encode = function encode (data) {\n if (!this.genPoly) {\n throw new Error('Encoder not initialized')\n }\n\n // Calculate EC for this data block\n // extends data size to data+genPoly size\n const paddedData = new Uint8Array(data.length + this.degree)\n paddedData.set(data)\n\n // The error correction codewords are the remainder after dividing the data codewords\n // by a generator polynomial\n const remainder = Polynomial.mod(paddedData, this.genPoly)\n\n // return EC data blocks (last n byte, where n is the degree of genPoly)\n // If coefficients number in remainder are less than genPoly degree,\n // pad with 0s to the left to reach the needed number of coefficients\n const start = this.degree - remainder.length\n if (start > 0) {\n const buff = new Uint8Array(this.degree)\n buff.set(remainder, start)\n\n return buff\n }\n\n return remainder\n}\n\nmodule.exports = ReedSolomonEncoder\n","const numeric = '[0-9]+'\nconst alphanumeric = '[A-Z $%*+\\\\-./:]+'\nlet kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +\n '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +\n '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +\n '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'\nkanji = kanji.replace(/u/g, '\\\\u')\n\nconst byte = '(?:(?![A-Z0-9 $%*+\\\\-./:]|' + kanji + ')(?:.|[\\r\\n]))+'\n\nexports.KANJI = new RegExp(kanji, 'g')\nexports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\\\-./:]+', 'g')\nexports.BYTE = new RegExp(byte, 'g')\nexports.NUMERIC = new RegExp(numeric, 'g')\nexports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')\n\nconst TEST_KANJI = new RegExp('^' + kanji + '$')\nconst TEST_NUMERIC = new RegExp('^' + numeric + '$')\nconst TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\\\-./:]+$')\n\nexports.testKanji = function testKanji (str) {\n return TEST_KANJI.test(str)\n}\n\nexports.testNumeric = function testNumeric (str) {\n return TEST_NUMERIC.test(str)\n}\n\nexports.testAlphanumeric = function testAlphanumeric (str) {\n return TEST_ALPHANUMERIC.test(str)\n}\n","const Mode = require('./mode')\nconst NumericData = require('./numeric-data')\nconst AlphanumericData = require('./alphanumeric-data')\nconst ByteData = require('./byte-data')\nconst KanjiData = require('./kanji-data')\nconst Regex = require('./regex')\nconst Utils = require('./utils')\nconst dijkstra = require('dijkstrajs')\n\n/**\n * Returns UTF8 byte length\n *\n * @param {String} str Input string\n * @return {Number} Number of byte\n */\nfunction getStringByteLength (str) {\n return unescape(encodeURIComponent(str)).length\n}\n\n/**\n * Get a list of segments of the specified mode\n * from a string\n *\n * @param {Mode} mode Segment mode\n * @param {String} str String to process\n * @return {Array} Array of object with segments data\n */\nfunction getSegments (regex, mode, str) {\n const segments = []\n let result\n\n while ((result = regex.exec(str)) !== null) {\n segments.push({\n data: result[0],\n index: result.index,\n mode: mode,\n length: result[0].length\n })\n }\n\n return segments\n}\n\n/**\n * Extracts a series of segments with the appropriate\n * modes from a string\n *\n * @param {String} dataStr Input string\n * @return {Array} Array of object with segments data\n */\nfunction getSegmentsFromString (dataStr) {\n const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)\n const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)\n let byteSegs\n let kanjiSegs\n\n if (Utils.isKanjiModeEnabled()) {\n byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)\n kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)\n } else {\n byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)\n kanjiSegs = []\n }\n\n const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)\n\n return segs\n .sort(function (s1, s2) {\n return s1.index - s2.index\n })\n .map(function (obj) {\n return {\n data: obj.data,\n mode: obj.mode,\n length: obj.length\n }\n })\n}\n\n/**\n * Returns how many bits are needed to encode a string of\n * specified length with the specified mode\n *\n * @param {Number} length String length\n * @param {Mode} mode Segment mode\n * @return {Number} Bit length\n */\nfunction getSegmentBitsLength (length, mode) {\n switch (mode) {\n case Mode.NUMERIC:\n return NumericData.getBitsLength(length)\n case Mode.ALPHANUMERIC:\n return AlphanumericData.getBitsLength(length)\n case Mode.KANJI:\n return KanjiData.getBitsLength(length)\n case Mode.BYTE:\n return ByteData.getBitsLength(length)\n }\n}\n\n/**\n * Merges adjacent segments which have the same mode\n *\n * @param {Array} segs Array of object with segments data\n * @return {Array} Array of object with segments data\n */\nfunction mergeSegments (segs) {\n return segs.reduce(function (acc, curr) {\n const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null\n if (prevSeg && prevSeg.mode === curr.mode) {\n acc[acc.length - 1].data += curr.data\n return acc\n }\n\n acc.push(curr)\n return acc\n }, [])\n}\n\n/**\n * Generates a list of all possible nodes combination which\n * will be used to build a segments graph.\n *\n * Nodes are divided by groups. Each group will contain a list of all the modes\n * in which is possible to encode the given text.\n *\n * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.\n * The group for '12345' will contain then 3 objects, one for each\n * possible encoding mode.\n *\n * Each node represents a possible segment.\n *\n * @param {Array} segs Array of object with segments data\n * @return {Array} Array of object with segments data\n */\nfunction buildNodes (segs) {\n const nodes = []\n for (let i = 0; i < segs.length; i++) {\n const seg = segs[i]\n\n switch (seg.mode) {\n case Mode.NUMERIC:\n nodes.push([seg,\n { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },\n { data: seg.data, mode: Mode.BYTE, length: seg.length }\n ])\n break\n case Mode.ALPHANUMERIC:\n nodes.push([seg,\n { data: seg.data, mode: Mode.BYTE, length: seg.length }\n ])\n break\n case Mode.KANJI:\n nodes.push([seg,\n { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }\n ])\n break\n case Mode.BYTE:\n nodes.push([\n { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }\n ])\n }\n }\n\n return nodes\n}\n\n/**\n * Builds a graph from a list of nodes.\n * All segments in each node group will be connected with all the segments of\n * the next group and so on.\n *\n * At each connection will be assigned a weight depending on the\n * segment's byte length.\n *\n * @param {Array} nodes Array of object with segments data\n * @param {Number} version QR Code version\n * @return {Object} Graph of all possible segments\n */\nfunction buildGraph (nodes, version) {\n const table = {}\n const graph = { start: {} }\n let prevNodeIds = ['start']\n\n for (let i = 0; i < nodes.length; i++) {\n const nodeGroup = nodes[i]\n const currentNodeIds = []\n\n for (let j = 0; j < nodeGroup.length; j++) {\n const node = nodeGroup[j]\n const key = '' + i + j\n\n currentNodeIds.push(key)\n table[key] = { node: node, lastCount: 0 }\n graph[key] = {}\n\n for (let n = 0; n < prevNodeIds.length; n++) {\n const prevNodeId = prevNodeIds[n]\n\n if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {\n graph[prevNodeId][key] =\n getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -\n getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)\n\n table[prevNodeId].lastCount += node.length\n } else {\n if (table[prevNodeId]) table[prevNodeId].lastCount = node.length\n\n graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +\n 4 + Mode.getCharCountIndicator(node.mode, version) // switch cost\n }\n }\n }\n\n prevNodeIds = currentNodeIds\n }\n\n for (let n = 0; n < prevNodeIds.length; n++) {\n graph[prevNodeIds[n]].end = 0\n }\n\n return { map: graph, table: table }\n}\n\n/**\n * Builds a segment from a specified data and mode.\n * If a mode is not specified, the more suitable will be used.\n *\n * @param {String} data Input data\n * @param {Mode | String} modesHint Data mode\n * @return {Segment} Segment\n */\nfunction buildSingleSegment (data, modesHint) {\n let mode\n const bestMode = Mode.getBestModeForData(data)\n\n mode = Mode.from(modesHint, bestMode)\n\n // Make sure data can be encoded\n if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {\n throw new Error('\"' + data + '\"' +\n ' cannot be encoded with mode ' + Mode.toString(mode) +\n '.\\n Suggested mode is: ' + Mode.toString(bestMode))\n }\n\n // Use Mode.BYTE if Kanji support is disabled\n if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {\n mode = Mode.BYTE\n }\n\n switch (mode) {\n case Mode.NUMERIC:\n return new NumericData(data)\n\n case Mode.ALPHANUMERIC:\n return new AlphanumericData(data)\n\n case Mode.KANJI:\n return new KanjiData(data)\n\n case Mode.BYTE:\n return new ByteData(data)\n }\n}\n\n/**\n * Builds a list of segments from an array.\n * Array can contain Strings or Objects with segment's info.\n *\n * For each item which is a string, will be generated a segment with the given\n * string and the more appropriate encoding mode.\n *\n * For each item which is an object, will be generated a segment with the given\n * data and mode.\n * Objects must contain at least the property \"data\".\n * If property \"mode\" is not present, the more suitable mode will be used.\n *\n * @param {Array} array Array of objects with segments data\n * @return {Array} Array of Segments\n */\nexports.fromArray = function fromArray (array) {\n return array.reduce(function (acc, seg) {\n if (typeof seg === 'string') {\n acc.push(buildSingleSegment(seg, null))\n } else if (seg.data) {\n acc.push(buildSingleSegment(seg.data, seg.mode))\n }\n\n return acc\n }, [])\n}\n\n/**\n * Builds an optimized sequence of segments from a string,\n * which will produce the shortest possible bitstream.\n *\n * @param {String} data Input string\n * @param {Number} version QR Code version\n * @return {Array} Array of segments\n */\nexports.fromString = function fromString (data, version) {\n const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())\n\n const nodes = buildNodes(segs)\n const graph = buildGraph(nodes, version)\n const path = dijkstra.find_path(graph.map, 'start', 'end')\n\n const optimizedSegs = []\n for (let i = 1; i < path.length - 1; i++) {\n optimizedSegs.push(graph.table[path[i]].node)\n }\n\n return exports.fromArray(mergeSegments(optimizedSegs))\n}\n\n/**\n * Splits a string in various segments with the modes which\n * best represent their content.\n * The produced segments are far from being optimized.\n * The output of this function is only used to estimate a QR Code version\n * which may contain the data.\n *\n * @param {string} data Input string\n * @return {Array} Array of segments\n */\nexports.rawSplit = function rawSplit (data) {\n return exports.fromArray(\n getSegmentsFromString(data, Utils.isKanjiModeEnabled())\n )\n}\n","let toSJISFunction\nconst CODEWORDS_COUNT = [\n 0, // Not used\n 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,\n 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,\n 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,\n 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706\n]\n\n/**\n * Returns the QR Code size for the specified version\n *\n * @param {Number} version QR Code version\n * @return {Number} size of QR code\n */\nexports.getSymbolSize = function getSymbolSize (version) {\n if (!version) throw new Error('\"version\" cannot be null or undefined')\n if (version < 1 || version > 40) throw new Error('\"version\" should be in range from 1 to 40')\n return version * 4 + 17\n}\n\n/**\n * Returns the total number of codewords used to store data and EC information.\n *\n * @param {Number} version QR Code version\n * @return {Number} Data length in bits\n */\nexports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {\n return CODEWORDS_COUNT[version]\n}\n\n/**\n * Encode data with Bose-Chaudhuri-Hocquenghem\n *\n * @param {Number} data Value to encode\n * @return {Number} Encoded value\n */\nexports.getBCHDigit = function (data) {\n let digit = 0\n\n while (data !== 0) {\n digit++\n data >>>= 1\n }\n\n return digit\n}\n\nexports.setToSJISFunction = function setToSJISFunction (f) {\n if (typeof f !== 'function') {\n throw new Error('\"toSJISFunc\" is not a valid function.')\n }\n\n toSJISFunction = f\n}\n\nexports.isKanjiModeEnabled = function () {\n return typeof toSJISFunction !== 'undefined'\n}\n\nexports.toSJIS = function toSJIS (kanji) {\n return toSJISFunction(kanji)\n}\n","/**\n * Check if QR Code version is valid\n *\n * @param {Number} version QR Code version\n * @return {Boolean} true if valid version, false otherwise\n */\nexports.isValid = function isValid (version) {\n return !isNaN(version) && version >= 1 && version <= 40\n}\n","const Utils = require('./utils')\nconst ECCode = require('./error-correction-code')\nconst ECLevel = require('./error-correction-level')\nconst Mode = require('./mode')\nconst VersionCheck = require('./version-check')\n\n// Generator polynomial used to encode version information\nconst G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)\nconst G18_BCH = Utils.getBCHDigit(G18)\n\nfunction getBestVersionForDataLength (mode, length, errorCorrectionLevel) {\n for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {\n if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {\n return currentVersion\n }\n }\n\n return undefined\n}\n\nfunction getReservedBitsCount (mode, version) {\n // Character count indicator + mode indicator bits\n return Mode.getCharCountIndicator(mode, version) + 4\n}\n\nfunction getTotalBitsFromDataArray (segments, version) {\n let totalBits = 0\n\n segments.forEach(function (data) {\n const reservedBits = getReservedBitsCount(data.mode, version)\n totalBits += reservedBits + data.getBitsLength()\n })\n\n return totalBits\n}\n\nfunction getBestVersionForMixedData (segments, errorCorrectionLevel) {\n for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {\n const length = getTotalBitsFromDataArray(segments, currentVersion)\n if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {\n return currentVersion\n }\n }\n\n return undefined\n}\n\n/**\n * Returns version number from a value.\n * If value is not a valid version, returns defaultValue\n *\n * @param {Number|String} value QR Code version\n * @param {Number} defaultValue Fallback value\n * @return {Number} QR Code version number\n */\nexports.from = function from (value, defaultValue) {\n if (VersionCheck.isValid(value)) {\n return parseInt(value, 10)\n }\n\n return defaultValue\n}\n\n/**\n * Returns how much data can be stored with the specified QR code version\n * and error correction level\n *\n * @param {Number} version QR Code version (1-40)\n * @param {Number} errorCorrectionLevel Error correction level\n * @param {Mode} mode Data mode\n * @return {Number} Quantity of storable data\n */\nexports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {\n if (!VersionCheck.isValid(version)) {\n throw new Error('Invalid QR Code version')\n }\n\n // Use Byte mode as default\n if (typeof mode === 'undefined') mode = Mode.BYTE\n\n // Total codewords for this QR code version (Data + Error correction)\n const totalCodewords = Utils.getSymbolTotalCodewords(version)\n\n // Total number of error correction codewords\n const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n\n // Total number of data codewords\n const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8\n\n if (mode === Mode.MIXED) return dataTotalCodewordsBits\n\n const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)\n\n // Return max number of storable codewords\n switch (mode) {\n case Mode.NUMERIC:\n return Math.floor((usableBits / 10) * 3)\n\n case Mode.ALPHANUMERIC:\n return Math.floor((usableBits / 11) * 2)\n\n case Mode.KANJI:\n return Math.floor(usableBits / 13)\n\n case Mode.BYTE:\n default:\n return Math.floor(usableBits / 8)\n }\n}\n\n/**\n * Returns the minimum version needed to contain the amount of data\n *\n * @param {Segment} data Segment of data\n * @param {Number} [errorCorrectionLevel=H] Error correction level\n * @param {Mode} mode Data mode\n * @return {Number} QR Code version\n */\nexports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {\n let seg\n\n const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)\n\n if (Array.isArray(data)) {\n if (data.length > 1) {\n return getBestVersionForMixedData(data, ecl)\n }\n\n if (data.length === 0) {\n return 1\n }\n\n seg = data[0]\n } else {\n seg = data\n }\n\n return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)\n}\n\n/**\n * Returns version information with relative error correction bits\n *\n * The version information is included in QR Code symbols of version 7 or larger.\n * It consists of an 18-bit sequence containing 6 data bits,\n * with 12 error correction bits calculated using the (18, 6) Golay code.\n *\n * @param {Number} version QR Code version\n * @return {Number} Encoded version info bits\n */\nexports.getEncodedBits = function getEncodedBits (version) {\n if (!VersionCheck.isValid(version) || version < 7) {\n throw new Error('Invalid QR Code version')\n }\n\n let d = version << 12\n\n while (Utils.getBCHDigit(d) - G18_BCH >= 0) {\n d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))\n }\n\n return (version << 12) | d\n}\n","const Utils = require('./utils')\n\nfunction clearCanvas (ctx, canvas, size) {\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n if (!canvas.style) canvas.style = {}\n canvas.height = size\n canvas.width = size\n canvas.style.height = size + 'px'\n canvas.style.width = size + 'px'\n}\n\nfunction getCanvasElement () {\n try {\n return document.createElement('canvas')\n } catch (e) {\n throw new Error('You need to specify a canvas element')\n }\n}\n\nexports.render = function render (qrData, canvas, options) {\n let opts = options\n let canvasEl = canvas\n\n if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {\n opts = canvas\n canvas = undefined\n }\n\n if (!canvas) {\n canvasEl = getCanvasElement()\n }\n\n opts = Utils.getOptions(opts)\n const size = Utils.getImageWidth(qrData.modules.size, opts)\n\n const ctx = canvasEl.getContext('2d')\n const image = ctx.createImageData(size, size)\n Utils.qrToImageData(image.data, qrData, opts)\n\n clearCanvas(ctx, canvasEl, size)\n ctx.putImageData(image, 0, 0)\n\n return canvasEl\n}\n\nexports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {\n let opts = options\n\n if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {\n opts = canvas\n canvas = undefined\n }\n\n if (!opts) opts = {}\n\n const canvasEl = exports.render(qrData, canvas, opts)\n\n const type = opts.type || 'image/png'\n const rendererOpts = opts.rendererOpts || {}\n\n return canvasEl.toDataURL(type, rendererOpts.quality)\n}\n","const Utils = require('./utils')\n\nfunction getColorAttrib (color, attrib) {\n const alpha = color.a / 255\n const str = attrib + '=\"' + color.hex + '\"'\n\n return alpha < 1\n ? str + ' ' + attrib + '-opacity=\"' + alpha.toFixed(2).slice(1) + '\"'\n : str\n}\n\nfunction svgCmd (cmd, x, y) {\n let str = cmd + x\n if (typeof y !== 'undefined') str += ' ' + y\n\n return str\n}\n\nfunction qrToPath (data, size, margin) {\n let path = ''\n let moveBy = 0\n let newRow = false\n let lineLength = 0\n\n for (let i = 0; i < data.length; i++) {\n const col = Math.floor(i % size)\n const row = Math.floor(i / size)\n\n if (!col && !newRow) newRow = true\n\n if (data[i]) {\n lineLength++\n\n if (!(i > 0 && col > 0 && data[i - 1])) {\n path += newRow\n ? svgCmd('M', col + margin, 0.5 + row + margin)\n : svgCmd('m', moveBy, 0)\n\n moveBy = 0\n newRow = false\n }\n\n if (!(col + 1 < size && data[i + 1])) {\n path += svgCmd('h', lineLength)\n lineLength = 0\n }\n } else {\n moveBy++\n }\n }\n\n return path\n}\n\nexports.render = function render (qrData, options, cb) {\n const opts = Utils.getOptions(options)\n const size = qrData.modules.size\n const data = qrData.modules.data\n const qrcodesize = size + opts.margin * 2\n\n const bg = !opts.color.light.a\n ? ''\n : ''\n\n const path =\n ''\n\n const viewBox = 'viewBox=\"' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '\"'\n\n const width = !opts.width ? '' : 'width=\"' + opts.width + '\" height=\"' + opts.width + '\" '\n\n const svgTag = '' + bg + path + '\\n'\n\n if (typeof cb === 'function') {\n cb(null, svgTag)\n }\n\n return svgTag\n}\n","function hex2rgba (hex) {\n if (typeof hex === 'number') {\n hex = hex.toString()\n }\n\n if (typeof hex !== 'string') {\n throw new Error('Color should be defined as hex string')\n }\n\n let hexCode = hex.slice().replace('#', '').split('')\n if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {\n throw new Error('Invalid hex color: ' + hex)\n }\n\n // Convert from short to long form (fff -> ffffff)\n if (hexCode.length === 3 || hexCode.length === 4) {\n hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {\n return [c, c]\n }))\n }\n\n // Add default alpha value\n if (hexCode.length === 6) hexCode.push('F', 'F')\n\n const hexValue = parseInt(hexCode.join(''), 16)\n\n return {\n r: (hexValue >> 24) & 255,\n g: (hexValue >> 16) & 255,\n b: (hexValue >> 8) & 255,\n a: hexValue & 255,\n hex: '#' + hexCode.slice(0, 6).join('')\n }\n}\n\nexports.getOptions = function getOptions (options) {\n if (!options) options = {}\n if (!options.color) options.color = {}\n\n const margin = typeof options.margin === 'undefined' ||\n options.margin === null ||\n options.margin < 0\n ? 4\n : options.margin\n\n const width = options.width && options.width >= 21 ? options.width : undefined\n const scale = options.scale || 4\n\n return {\n width: width,\n scale: width ? 4 : scale,\n margin: margin,\n color: {\n dark: hex2rgba(options.color.dark || '#000000ff'),\n light: hex2rgba(options.color.light || '#ffffffff')\n },\n type: options.type,\n rendererOpts: options.rendererOpts || {}\n }\n}\n\nexports.getScale = function getScale (qrSize, opts) {\n return opts.width && opts.width >= qrSize + opts.margin * 2\n ? opts.width / (qrSize + opts.margin * 2)\n : opts.scale\n}\n\nexports.getImageWidth = function getImageWidth (qrSize, opts) {\n const scale = exports.getScale(qrSize, opts)\n return Math.floor((qrSize + opts.margin * 2) * scale)\n}\n\nexports.qrToImageData = function qrToImageData (imgData, qr, opts) {\n const size = qr.modules.size\n const data = qr.modules.data\n const scale = exports.getScale(size, opts)\n const symbolSize = Math.floor((size + opts.margin * 2) * scale)\n const scaledMargin = opts.margin * scale\n const palette = [opts.color.light, opts.color.dark]\n\n for (let i = 0; i < symbolSize; i++) {\n for (let j = 0; j < symbolSize; j++) {\n let posDst = (i * symbolSize + j) * 4\n let pxColor = opts.color.light\n\n if (i >= scaledMargin && j >= scaledMargin &&\n i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {\n const iSrc = Math.floor((i - scaledMargin) / scale)\n const jSrc = Math.floor((j - scaledMargin) / scale)\n pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]\n }\n\n imgData[posDst++] = pxColor.r\n imgData[posDst++] = pxColor.g\n imgData[posDst++] = pxColor.b\n imgData[posDst] = pxColor.a\n }\n }\n}\n","/**\n * @license React\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\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(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 z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(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){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(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(ra,\nsa);z[b]=new v(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(ra,sa);z[b]=new v(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(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(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 ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction 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 A({},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 ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(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\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(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 cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!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,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({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 ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(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}}var wb=null;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(p(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>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=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)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=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){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 Ne(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)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=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&&Ne(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&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;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}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)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=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(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&128))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 Nh=[];\nfunction Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"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[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,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=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(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.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(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.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;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 yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(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 bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=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.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}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}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\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","// 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","// A port of an algorithm by Johannes Baagøe , 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 \n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n var me = this, mash = Mash();\n\n me.next = function() {\n var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n me.s0 = me.s1;\n me.s1 = me.s2;\n return me.s2 = t - (me.c = t | 0);\n };\n\n // Apply the seeding algorithm from Baagoe.\n me.c = 1;\n me.s0 = mash(' ');\n me.s1 = mash(' ');\n me.s2 = mash(' ');\n me.s0 -= mash(seed);\n if (me.s0 < 0) { me.s0 += 1; }\n me.s1 -= mash(seed);\n if (me.s1 < 0) { me.s1 += 1; }\n me.s2 -= mash(seed);\n if (me.s2 < 0) { me.s2 += 1; }\n mash = null;\n}\n\nfunction copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new Alea(seed),\n state = opts && opts.state,\n prng = xg.next;\n prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n prng.double = function() {\n return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n };\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nfunction Mash() {\n var n = 0xefc8249d;\n\n var mash = function(data) {\n data = String(data);\n for (var i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n var h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n };\n\n return mash;\n}\n\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.alea = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"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","// 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 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 \"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 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","/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n(function (global, pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\n\nvar width = 256, // each RC4 output is 0 <= x < 256\n chunks = 6, // at least six RC4 outputs for each double\n digits = 52, // there are 52 significant digits in a double\n rngname = 'random', // rngname: name for Math.random and Math.seedrandom\n startdenom = math.pow(width, chunks),\n significance = math.pow(2, digits),\n overflow = significance * 2,\n mask = width - 1,\n nodecrypto; // node.js crypto module, initialized at the bottom.\n\n//\n// seedrandom()\n// This is the seedrandom function described above.\n//\nfunction seedrandom(seed, options, callback) {\n var key = [];\n options = (options == true) ? { entropy: true } : (options || {});\n\n // Flatten the seed string or build one from local entropy if needed.\n var shortseed = mixkey(flatten(\n options.entropy ? [seed, tostring(pool)] :\n (seed == null) ? autoseed() : seed, 3), key);\n\n // Use the seed to initialize an ARC4 generator.\n var arc4 = new ARC4(key);\n\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n var prng = function() {\n var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48\n d = startdenom, // and denominator d = 2 ^ 48.\n x = 0; // and no 'extra last byte'.\n while (n < significance) { // Fill up all significant digits by\n n = (n + x) * width; // shifting numerator and\n d *= width; // denominator and generating a\n x = arc4.g(1); // new least-significant-byte.\n }\n while (n >= overflow) { // To avoid rounding up, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n };\n\n prng.int32 = function() { return arc4.g(4) | 0; }\n prng.quick = function() { return arc4.g(4) / 0x100000000; }\n prng.double = prng;\n\n // Mix the randomness into accumulated entropy.\n mixkey(tostring(arc4.S), pool);\n\n // Calling convention: what to return as a function of prng, seed, is_math.\n return (options.pass || callback ||\n function(prng, seed, is_math_call, state) {\n if (state) {\n // Load the arc4 state from the given state if it has an S array.\n if (state.S) { copy(state, arc4); }\n // Only provide the .state method if requested via options.state.\n prng.state = function() { return copy(arc4, {}); }\n }\n\n // If called as a method of Math (Math.seedrandom()), mutate\n // Math.random because that is how seedrandom.js has worked since v1.0.\n if (is_math_call) { math[rngname] = prng; return seed; }\n\n // Otherwise, it is a newer calling convention, so return the\n // prng directly.\n else return prng;\n })(\n prng,\n shortseed,\n 'global' in options ? options.global : (this == math),\n options.state);\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\nfunction ARC4(key) {\n var t, keylen = key.length,\n me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i < width) {\n s[i] = i++;\n }\n for (i = 0; i < width; i++) {\n s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];\n s[j] = t;\n }\n\n // The \"g\" method returns the next (count) outputs as one number.\n (me.g = function(count) {\n // Using instance members instead of closure state nearly doubles speed.\n var t, r = 0,\n i = me.i, j = me.j, s = me.S;\n while (count--) {\n t = s[i = mask & (i + 1)];\n r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];\n }\n me.i = i; me.j = j;\n return r;\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n })(width);\n}\n\n//\n// copy()\n// Copies internal state of ARC4 to or from a plain object.\n//\nfunction copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = f.S.slice();\n return t;\n};\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\nfunction flatten(obj, depth) {\n var result = [], typ = (typeof obj), prop;\n if (depth && typ == 'object') {\n for (prop in obj) {\n try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}\n }\n }\n return (result.length ? result : typ == 'string' ? obj : obj + '\\0');\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\nfunction mixkey(seed, key) {\n var stringseed = seed + '', smear, j = 0;\n while (j < stringseed.length) {\n key[mask & j] =\n mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));\n }\n return tostring(key);\n}\n\n//\n// autoseed()\n// Returns an object for autoseeding, using window.crypto and Node crypto\n// module if available.\n//\nfunction autoseed() {\n try {\n var out;\n if (nodecrypto && (out = nodecrypto.randomBytes)) {\n // The use of 'out' to remember randomBytes makes tight minified code.\n out = out(width);\n } else {\n out = new Uint8Array(width);\n (global.crypto || global.msCrypto).getRandomValues(out);\n }\n return tostring(out);\n } catch (e) {\n var browser = global.navigator,\n plugins = browser && browser.plugins;\n return [+new Date, global, plugins, global.screen, tostring(pool)];\n }\n}\n\n//\n// tostring()\n// Converts an array of charcodes to a string\n//\nfunction tostring(a) {\n return String.fromCharCode.apply(0, a);\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool. Because we do\n// not want to interfere with deterministic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(math.random(), pool);\n\n//\n// Nodejs and AMD support: export the implementation as a module using\n// either convention.\n//\nif ((typeof module) == 'object' && module.exports) {\n module.exports = seedrandom;\n // When in node.js, try using crypto package for autoseeding.\n try {\n nodecrypto = require('crypto');\n } catch (ex) {}\n} else if ((typeof define) == 'function' && define.amd) {\n define(function() { return seedrandom; });\n} else {\n // When included as a plain script, set up Math.seedrandom global.\n math['seed' + rngname] = seedrandom;\n}\n\n\n// End anonymous scope, and pass initial values.\n})(\n // global: `self` in browsers (including strict mode and web workers),\n // otherwise `this` in Node and other environments\n (typeof self !== 'undefined') ? self : this,\n [], // pool: entropy pool starts empty\n Math // math: package containing random, pow, and seedrandom\n);\n","/*\n * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\nvar _ = require('./es6_');\n\n/**\n * Performs an deep extend on the objects, from right to left.\n * @private\n * @param {Object[]} objects - An array of JS objects\n * @param {Function} collision - A function to be called when a merge collision happens.\n * @param {string[]} path - (for internal use) An array of strings which is the current path down the object when this is called recursively.\n * @returns {Object}\n */\nfunction deepExtend(objects, collision, path) {\n if (objects == null)\n return {};\n\n var src, copyIsArray, copy, name, options, clone,\n target = objects[0] || {},\n i = 1,\n length = objects.length;\n\n path = path || [];\n\n // Handle case when target is a string or something (possible in deep copy)\n if ( typeof target !== 'object' ) {\n target = {};\n }\n\n for ( ; i < length; i++) {\n // Only deal with non-null/undefined values\n if ( (options = objects[ i ]) != null ) {\n // Extend the base object\n for (name in options) {\n if (!options.hasOwnProperty(name))\n continue;\n if (name === '__proto__')\n continue;\n\n src = target[name];\n copy = options[name];\n\n // Prevent never-ending loop\n if (target === copy) {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays\n if ( copy && ( _.isPlainObject(copy) || (copyIsArray = _.isArray(copy)) ) ) {\n if ( copyIsArray ) {\n copyIsArray = false;\n clone = src && _.isArray(src) ? src : [];\n } else {\n clone = src && _.isPlainObject(src) ? src : {};\n }\n\n var nextPath = path.slice(0);\n nextPath.push(name);\n\n // Never move original objects, clone them\n target[ name ] = deepExtend( [clone, copy], collision, nextPath );\n\n // Don't bring in undefined values\n } else if ( copy !== undefined ) {\n if (src != null && typeof collision == 'function') {\n collision({target: target, copy: options, path: path, key: name});\n }\n target[ name ] = copy;\n }\n }\n }\n }\n\n return target;\n}\n\nmodule.exports = deepExtend;\n","/*\n * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\nconst ChangeCase = require('change-case')\n\nconst reduce = function(obj, f, accumulator_init) {\n return Object.keys(obj || {}).reduce((accumulator, key) => {\n let value = obj[key]\n return f(accumulator, value, key, obj)\n }, accumulator_init)\n}\n\nconst forEach = function(obj, f) {\n Object.keys(obj || {}).forEach((key) => {\n let value = obj[key]\n f(value, key)\n });\n}\n\n// Note: This is a crappy version to a certain extent... don't use with Strings, for example...\nconst clone = function(object) {\n return Object.assign(new object.constructor(), object)\n}\n\nconst cloneDeep = function(obj) {\n if(obj === null || obj === undefined || typeof obj !== 'object') {\n return obj\n }\n\n if(obj instanceof Array) {\n return obj.reduce((arr, item, i) => {\n arr[i] = cloneDeep(item)\n return arr\n }, [])\n }\n\n if(obj instanceof Object) {\n return Object.keys(obj || {}).reduce((cpObj, key) => {\n cpObj[key] = cloneDeep(obj[key])\n return cpObj\n }, {})\n }\n}\n\nconst isObject = function(value) {\n const type = typeof value\n return value != null && (type === 'object' || type === 'function')\n}\n\nconst isString = function(obj) {\n return typeof obj === 'string' || obj instanceof String\n}\n\nconst isArray = function(obj) {\n return Array.isArray(obj)\n}\n\nconst isEmpty = function(obj) {\n return [Object, Array].includes((obj || {}).constructor) && !Object.entries((obj || {})).length\n}\n\nfunction isPlainObject(value) {\n if (typeof value !== 'object' || value === null || Object.prototype.toString.call(value) !== '[object Object]') {\n return false\n }\n if (Object.getPrototypeOf(value) === null) {\n return true\n }\n let proto = value\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto)\n }\n return Object.getPrototypeOf(value) === proto\n}\n\nconst filter = function (arr, filter) {\n if (typeof(filter) !== 'function') {\n throw(\"filter is not a function\")\n }\n if (typeof arr === 'undefined') {\n return []\n }\n return arr.filter(filter)\n}\n\nconst assign = function () {\n let args = Array.prototype.slice.call(arguments)\n args.unshift({})\n return Object.assign(...args)\n}\n\n/* global Set */\nconst pull = function (arr, ...removeList){\n var removeSet = new Set(removeList)\n for (let i=arr.length-1;i>=0;i--) {\n if (removeSet.has(arr[i])) {\n arr.splice(i, 1)\n }\n }\n}\n\nconst unique = function (arr){\n return [...new Set(arr)]\n}\n\nconst upperFirst = function (str) {\n return str ? str[0].toUpperCase() + str.substr(1) : ''\n}\n\nconst matchFn = function(inputObj, testObj) {\n if (isObject(testObj)) {\n return Object.keys(testObj).every((key) => matchFn(inputObj[key], testObj[key]))\n }\n else {\n return inputObj == testObj\n }\n}\n\nconst matches = function (matchObj) {\n let cloneObj = cloneDeep(matchObj)\n let matchesFn = (inputObj) => matchFn(inputObj, cloneObj)\n return matchesFn\n}\n\nconst DEFAULT_OPTIONS = {\n transform: ChangeCase.camelCaseTransformMerge\n}\nconst changeDefaultCaseTransform = function (caseFunction, default_options) {\n return (caseToChange, options) => caseFunction(caseToChange, Object.assign({}, DEFAULT_OPTIONS, default_options, options))\n}\n\nmodule.exports = {\n each: forEach,\n forEach: forEach,\n forIn: forEach,\n keys: Object.keys,\n clone: clone,\n cloneDeep: cloneDeep,\n extend: Object.assign,\n isString: isString,\n isArray: isArray,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isEmpty: isEmpty,\n filter: filter,\n reduce: reduce,\n assign: assign,\n upperFirst: upperFirst,\n camelCase: changeDefaultCaseTransform(ChangeCase.camelCase),\n snakeCase: ChangeCase.snakeCase,\n kebabCase: ChangeCase.paramCase,\n pull: pull,\n matches: matches,\n unique: unique,\n}\n","/*\n * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\nvar _ = require('./es6_');\n\n/**\n * Takes an plain javascript object and will make a flat array of all the leaf nodes.\n * A leaf node in this context has a 'value' property. Potentially refactor this to\n * be more generic.\n * @private\n * @param {Object} properties - The plain object you want flattened into an array.\n * @param {Array} [to_ret=[]] - Properties array. This function is recursive therefore this is what gets passed along.\n * @return {Array}\n */\nfunction flattenProperties(properties, to_ret) {\n to_ret = to_ret || [];\n\n for(var name in properties) {\n if (properties.hasOwnProperty(name)) {\n // TODO: this is a bit fragile and arbitrary to stop when we get to a 'value' property.\n if (_.isPlainObject(properties[name]) && ('value' in properties[name])) {\n to_ret.push( properties[name] );\n } else if (_.isPlainObject(properties[name])) {\n flattenProperties(properties[name], to_ret);\n }\n }\n }\n\n return to_ret;\n}\n\n\nmodule.exports = flattenProperties;\n","/*\n * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\nconst defaults = require('./defaults');\n\nfunction createReferenceRegex(opts = {}) {\n const options = Object.assign({}, defaults, opts);\n\n return new RegExp(\n '\\\\' +\n options.opening_character +\n '([^' +\n options.closing_character +\n ']+)' +\n '\\\\' +\n options.closing_character, 'g'\n );\n}\n\nmodule.exports = createReferenceRegex;\n","/*\n * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\nconst defaults = {\n opening_character: '{',\n closing_character: '}',\n separator: '.'\n};\n\nmodule.exports = defaults;\n","/*\n * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n\nconst createRegex = require('./createReferenceRegex');\n\n/**\n * Checks if the value uses a value reference.\n * @memberof Dictionary\n * @param {string} value\n * @param {Object|RegExp} regexOrOptions\n * @returns {boolean} - True, if the value uses a value reference\n */\nfunction usesReference(value, regexOrOptions = {}) {\n const regex = regexOrOptions instanceof RegExp ? regexOrOptions : createRegex(regexOrOptions);\n\n if (typeof value === 'string') {\n return regex.test(value);\n }\n\n if (typeof value === 'object') {\n let hasReference = false;\n // iterate over each property in the object,\n // if any element passes the regex test,\n // the whole thing should be true\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n const element = value[key];\n let reference = usesReference(element, regexOrOptions);\n if (reference) {\n hasReference = true;\n break;\n }\n }\n }\n return hasReference;\n }\n\n return false;\n}\n\nmodule.exports = usesReference;\n","/**\n * @license React\n * use-sync-external-store-shim.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 e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.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 h=require(\"react\"),n=require(\"use-sync-external-store/shim\");function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q=\"function\"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);\nu(function(){f.hasValue=!0;f.value=d},[d]);w(d);return d};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\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\n'use strict';\n\n/**\n * Similar to invariant but only logs a warning if the condition is not met.\n * This can be used to log issues in development environments in critical\n * paths. Removing the logging code for production environments will keep the\n * same logic and follow the same code paths.\n */\n\nvar __DEV__ = process.env.NODE_ENV !== 'production';\n\nvar warning = function() {};\n\nif (__DEV__) {\n var printWarning = function printWarning(format, args) {\n var len = arguments.length;\n args = new Array(len > 1 ? len - 1 : 0);\n for (var key = 1; key < len; key++) {\n args[key - 1] = arguments[key];\n }\n var argIndex = 0;\n var message = 'Warning: ' +\n format.replace(/%s/g, function() {\n return args[argIndex++];\n });\n if (typeof console !== 'undefined') {\n console.error(message);\n }\n try {\n // --- Welcome to debugging React ---\n // This error was thrown as a convenience so that you can use this stack\n // to find the callsite that caused this warning to fire.\n throw new Error(message);\n } catch (x) {}\n }\n\n warning = function(condition, format, args) {\n var len = arguments.length;\n args = new Array(len > 2 ? len - 2 : 0);\n for (var key = 2; key < len; key++) {\n args[key - 2] = arguments[key];\n }\n if (format === undefined) {\n throw new Error(\n '`warning(condition, format, ...args)` requires a warning ' +\n 'message argument'\n );\n }\n if (!condition) {\n printWarning.apply(null, [format].concat(args));\n }\n };\n}\n\nmodule.exports = warning;\n","/*!\n\tCopyright (c) 2018 Jed Watson.\n\tLicensed under the MIT License (MIT), see\n\thttp://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) {\n\t\t\t\tclasses = appendClass(classes, parseValue(arg));\n\t\t\t}\n\t\t}\n\n\t\treturn classes;\n\t}\n\n\tfunction parseValue (arg) {\n\t\tif (typeof arg === 'string' || typeof arg === 'number') {\n\t\t\treturn arg;\n\t\t}\n\n\t\tif (typeof arg !== 'object') {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (Array.isArray(arg)) {\n\t\t\treturn classNames.apply(null, arg);\n\t\t}\n\n\t\tif (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {\n\t\t\treturn arg.toString();\n\t\t}\n\n\t\tvar classes = '';\n\n\t\tfor (var key in arg) {\n\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\tclasses = appendClass(classes, key);\n\t\t\t}\n\t\t}\n\n\t\treturn classes;\n\t}\n\n\tfunction appendClass (value, newClass) {\n\t\tif (!newClass) {\n\t\t\treturn value;\n\t\t}\n\t\n\t\tif (value) {\n\t\t\treturn value + ' ' + newClass;\n\t\t}\n\t\n\t\treturn value + newClass;\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","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","__webpack_require__.amdD = function () {\n\tthrow new Error('define cannot be used indirect');\n};","__webpack_require__.amdO = {};","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + \"34fcada1\" + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","var inProgress = {};\nvar dataWebpackPrefix = \"hacklify-app:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkhacklify_app\"] = self[\"webpackChunkhacklify_app\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `
`,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (args: LoaderFunctionArgs):\n | Promise\n | DataFunctionValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs):\n | Promise\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch(branches[i], decoded);\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n // No loader, nothing to initialize\n if (!m.route.loader) return true;\n // Explicitly opting-in to running on hydration\n if (m.route.loader.hydrate === true) return false;\n // Otherwise, initialized if hydrated with data or an error\n return (\n (loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined)\n );\n };\n\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { replace });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors)\n .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n .forEach(([routeId, error]) => {\n errors = Object.assign(errors || {}, { [routeId]: error });\n });\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\n }),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n v7_relativeSplatPath: boolean,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch {}\n\nexport interface DataRouteMatch extends RouteMatch {}\n\nexport interface DataRouterContextObject\n // Omit `future` since those can be pulled from the `router`\n // `NavigationContext` needs future since it doesn't have a `router` in all cases\n extends Omit {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n future: {\n v7_relativeSplatPath: boolean;\n };\n}\n\nexport const NavigationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a ``.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * ``.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey,\n Path extends string\n>(pattern: PathPattern | Path): PathMatch | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by ``s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, future, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n {outlet}\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params : Partial\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { future } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial | string,\n dataRouterState?: RemixRouter[\"state\"],\n future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under ) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent to .`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined ||\n matches[matches.length - 1].route.lazy !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState,\n future\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n \n {renderedMatches}\n \n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n

💿 Hey developer 👋

\n

\n You can provide a way better UX than this when your app throws errors\n by providing your own ErrorBoundary or{\" \"}\n errorElement prop on your route.\n

\n \n );\n }\n\n return (\n <>\n

Unexpected Application Error!

\n

{message}

\n {stack ?
{stack}
: null}\n {devInfo}\n \n );\n}\n\nconst defaultErrorElement = ;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error !== undefined ? (\n \n \n \n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n \n {children}\n \n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null,\n future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n\n if (match.route.id) {\n let { loaderData, errors } = dataRouterState;\n let needsToRunLoader =\n match.route.loader &&\n loaderData[match.route.id] === undefined &&\n (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error: any;\n let shouldRenderHydrateFallback = false;\n let errorElement: React.ReactNode | null = null;\n let hydrateFallbackElement: React.ReactNode | null = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\n \"route-fallback\",\n false,\n \"No `HydrateFallback` element provided to render during initial hydration\"\n );\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = ;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n \n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n \n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_relativeSplatPath: boolean;\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n // Only accept future flags relevant to rendering behavior\n // routing flags should be accessed via router.future\n future?: Partial>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n React.useEffect(() => {\n warning(\n fallbackElement == null || !router.future.v7_partialHydration,\n \"`` is deprecated when using \" +\n \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n );\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a