diff --git a/fireworks_detect/browser_policy.py b/fireworks_detect/browser_policy.py index 00b7ea8..1694177 100644 --- a/fireworks_detect/browser_policy.py +++ b/fireworks_detect/browser_policy.py @@ -1,6 +1,9 @@ """Public, advisory configuration for the optional browser processing beta.""" import json +from pathlib import Path + +from django.templatetags.static import static from django.urls import reverse @@ -11,7 +14,10 @@ SPEECH_LABEL_TERMS = ( "speech", "conversation", "narration", "monologue", "babbling", "whisper", "speaking", "speech synthesizer", ) -GATE_RESULTS = {"whitelist_match", "no_match", "unavailable", "error"} +GATE_RESULTS = {"whitelist_match", "speech_only", "no_match", "unavailable", "error"} +RELEVANCE_THRESHOLD = 0.5 +SPEECH_THRESHOLD = 0.5 +MODEL_VERSION = "google-yamnet-1" def browser_config(): @@ -31,15 +37,23 @@ def browser_policy(): "whitelist": [], "privacy_sensitive_speech": [], "thresholds": {}, + "model_version": MODEL_VERSION, + "model_url": "", + "class_map_url": "", } if not enabled: return policy rules = ClassificationRule.objects.filter(enabled=True).order_by("value") policy["whitelist"] = list(rules.filter(rule_type=ClassificationRule.RuleType.WHITELIST).values_list("value", flat=True)) - policy["privacy_sensitive_speech"] = [ - value for value in rules.filter(rule_type=ClassificationRule.RuleType.BLACKLIST).values_list("value", flat=True) - if any(term in value.lower() for term in SPEECH_LABEL_TERMS) - ] + class_map_path = Path(__file__).parent / "static/browser-yamnet/yamnet_class_map.json" + class_names = json.loads(class_map_path.read_text(encoding="utf-8")) + speech_classes = {name for name in class_names if any(term in name.lower() for term in SPEECH_LABEL_TERMS)} + speech_classes.update(value for value in rules.filter(rule_type=ClassificationRule.RuleType.BLACKLIST).values_list("value", flat=True) + if any(term in value.lower() for term in SPEECH_LABEL_TERMS)) + policy["privacy_sensitive_speech"] = sorted(speech_classes) + policy["thresholds"] = {"relevance": RELEVANCE_THRESHOLD, "speech": SPEECH_THRESHOLD} + policy["model_url"] = static("browser-yamnet/model.json") + policy["class_map_url"] = static("browser-yamnet/yamnet_class_map.json") return policy @@ -64,4 +78,7 @@ def advisory_browser_metadata(post_data): gate_result = submitted.get("browser_gate_result") if isinstance(gate_result, str) and gate_result in GATE_RESULTS: metadata["browser_gate_result"] = gate_result + speech = submitted.get("browser_speech_detected") + if type(speech) is bool: + metadata["browser_speech_detected"] = speech return metadata diff --git a/fireworks_detect/static/browser-yamnet/VERSION b/fireworks_detect/static/browser-yamnet/VERSION new file mode 100644 index 0000000..79c436f --- /dev/null +++ b/fireworks_detect/static/browser-yamnet/VERSION @@ -0,0 +1,3 @@ +google-yamnet-1 +source_revision=c651073789719ff39dcf51406733bbcaaafb43f2 +tensorflow=2.21.0 diff --git a/fireworks_detect/static/browser-yamnet/group1-shard1of4.bin b/fireworks_detect/static/browser-yamnet/group1-shard1of4.bin new file mode 100644 index 0000000..0366fb3 Binary files /dev/null and b/fireworks_detect/static/browser-yamnet/group1-shard1of4.bin differ diff --git a/fireworks_detect/static/browser-yamnet/group1-shard2of4.bin b/fireworks_detect/static/browser-yamnet/group1-shard2of4.bin new file mode 100644 index 0000000..9ac72a5 Binary files /dev/null and b/fireworks_detect/static/browser-yamnet/group1-shard2of4.bin differ diff --git a/fireworks_detect/static/browser-yamnet/group1-shard3of4.bin b/fireworks_detect/static/browser-yamnet/group1-shard3of4.bin new file mode 100644 index 0000000..f9eb843 Binary files /dev/null and b/fireworks_detect/static/browser-yamnet/group1-shard3of4.bin differ diff --git a/fireworks_detect/static/browser-yamnet/group1-shard4of4.bin b/fireworks_detect/static/browser-yamnet/group1-shard4of4.bin new file mode 100644 index 0000000..ccc34d5 Binary files /dev/null and b/fireworks_detect/static/browser-yamnet/group1-shard4of4.bin differ diff --git a/fireworks_detect/static/browser-yamnet/model.json b/fireworks_detect/static/browser-yamnet/model.json new file mode 100644 index 0000000..7064fe3 --- /dev/null +++ b/fireworks_detect/static/browser-yamnet/model.json @@ -0,0 +1 @@ +{"format": "graph-model", "generatedBy": "2.21.0", "convertedBy": "TensorFlow.js Converter v4.22.0", "signature": {"inputs": {"waveform": {"name": "waveform:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}]}}}, "outputs": {"predictions": {"name": "Identity_2:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}, {"size": "521"}]}}, "log_mel_spectrogram": {"name": "Identity_1:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}, {"size": "64"}]}}, "embeddings": {"name": "Identity:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}, {"size": "1024"}]}}}}, "modelTopology": {"node": [{"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/zeros_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/ones_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/start", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/delta", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_3", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}, {"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/strided_slice", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Const", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add/x", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape/shape_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_step", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_7", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}, {"size": "257"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/0_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "unknown_5", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_4", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/zeros_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/ones_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/start", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/delta", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_3", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}, {"size": "5"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/strided_slice", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Const", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add/x", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape/shape_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_step", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0/0", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv_recip", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "unknown", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "3"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split/split_dim", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_3", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "400"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_6", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}, {"size": "257"}]}}}}}, {"name": "unknown_8", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "257"}, {"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/y", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "3"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split/split_dim", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/3", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean/reduction_indices", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/MatMul/ReadVariableOp", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}, {"size": "521"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd/ReadVariableOp", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "521"}]}}}}}, {"name": "waveform", "op": "Placeholder", "attr": {"shape": {"shape": {"dim": [{"size": "-1"}]}}, "dtype": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "1"}, {"size": "32"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "32"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "32"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "32"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "32"}, {"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "64"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "64"}, {"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "128"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "128"}, {"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "128"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "128"}, {"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "256"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "256"}, {"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "256"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "256"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "1024"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "1024"}, {"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape/Shape", "op": "Shape", "input": ["waveform"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape/Shape", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_1", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_2"], "attr": {"begin_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "end_mask": {"i": "0"}, "shrink_axis_mask": {"i": "1"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract/Sub", "op": "Sub", "input": ["unknown", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.maximum_1/Maximum", "op": "Maximum", "input": ["StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice", "unknown"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.maximum/Maximum", "op": "Maximum", "input": ["unknown_2", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract/Sub"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_1/Sub", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.maximum_1/Maximum", "unknown"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.cast/Cast", "op": "Cast", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.subtract_1/Sub"], "attr": {"SrcT": {"type": "DT_INT32"}, "Truncate": {"b": false}, "DstT": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.cast/Cast", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv_recip"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.ceil/Ceil", "op": "Ceil", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.cast_1/Cast", "op": "Cast", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.ceil/Ceil"], "attr": {"SrcT": {"type": "DT_FLOAT"}, "Truncate": {"b": false}, "DstT": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply/Mul", "op": "Mul", "input": ["unknown_1", "StatefulPartitionedCall/yamnet_frames/tf.cast_1/Cast"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_2/Sub", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply/Mul", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_1/Sub"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add/AddV2", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.maximum/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_2/Sub"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0/0", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add/AddV2"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings_const_axis", "op": "Const", "input": ["^StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0"], "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings", "op": "ExpandDims", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings_const_axis"], "attr": {"Tdim": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad", "op": "Pad", "input": ["waveform", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings"], "attr": {"Tpaddings": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "op": "SplitV", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Shape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split/split_dim"], "attr": {"Tlen": {"type": "DT_INT32"}, "num_split": {"i": "3"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape/shape_1"], "attr": {"Tshape": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/sub_2", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/sub_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_step"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1_const_axis", "op": "Const", "input": ["^StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul"], "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add/x", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1", "op": "ExpandDims", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1_const_axis"], "attr": {"Tdim": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "op": "Maximum", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Const", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1", "op": "Range", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/start", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/delta"], "attr": {"Tidx": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length"], "attr": {"T": {"type": "DT_INT32"}, "axis": {"i": "0"}, "N": {"i": "2"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/StridedSlice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/zeros_like", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/ones_like"], "attr": {"begin_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "end_mask": {"i": "0"}, "shrink_axis_mask": {"i": "0"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul_1", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_2"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2/axis"], "attr": {"N": {"i": "3"}, "Tidx": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_1", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/StridedSlice", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape"], "attr": {"T": {"type": "DT_INT32"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add_1", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_3"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/GatherV2", "op": "GatherV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/strided_slice"], "attr": {"Tparams": {"type": "DT_FLOAT"}, "Taxis": {"type": "DT_INT32"}, "batch_dims": {"i": "0"}, "Tindices": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_4", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/GatherV2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2"], "attr": {"Tshape": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_1/Mul", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_4", "unknown_3"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape_1/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply_1/Mul"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape_1/Shape", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_1", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_2"], "attr": {"end_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "begin_mask": {"i": "0"}, "shrink_axis_mask": {"i": "1"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_4/Sub", "op": "Sub", "input": ["unknown_5", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_3/Sub", "op": "Sub", "input": ["unknown_4", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.subtract_3/Sub", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_5/Sub", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.subtract_4/Sub", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_5/Sub"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/0_1", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad", "op": "Pad", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply_1/Mul", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings"], "attr": {"Tpaddings": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul/MatMul", "op": "MatMul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad", "unknown_7"], "device": "/device:CPU:0", "attr": {"T": {"type": "DT_FLOAT"}, "transpose_b": {"b": false}, "grad_a": {"b": false}, "transpose_a": {"b": false}, "grad_b": {"b": false}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul_1/MatMul", "op": "MatMul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad", "unknown_6"], "device": "/device:CPU:0", "attr": {"T": {"type": "DT_FLOAT"}, "transpose_b": {"b": false}, "grad_b": {"b": false}, "transpose_a": {"b": false}, "grad_a": {"b": false}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_2/ArithmeticOptimizer/ReplaceMulWithSquare_Mul", "op": "Square", "input": ["StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul/MatMul"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_3/ArithmeticOptimizer/ReplaceMulWithSquare_Mul", "op": "Square", "input": ["StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul_1/MatMul"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.add/Add", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply_2/ArithmeticOptimizer/ReplaceMulWithSquare_Mul", "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_3/ArithmeticOptimizer/ReplaceMulWithSquare_Mul"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.sqrt/Sqrt", "op": "Sqrt", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.add/Add"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/AddV2", "op": "_FusedMatMul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.sqrt/Sqrt", "unknown_8", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/y"], "device": "/device:CPU:0", "attr": {"transpose_b": {"b": false}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA=="]}}, "num_args": {"i": "1"}, "transpose_a": {"b": false}, "epsilon": {"f": 0.0}, "leakyrelu_alpha": {"f": 0.2}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.log/Log", "op": "Log", "input": ["StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/AddV2"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "Identity_1", "op": "Identity", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.log/Log"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.log/Log"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "op": "SplitV", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Shape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split/split_dim"], "attr": {"Tlen": {"type": "DT_INT32"}, "num_split": {"i": "3"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape/shape_1"], "attr": {"T": {"type": "DT_INT32"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/sub_2", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/sub_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_step"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1_const_axis", "op": "Const", "input": ["^StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul"], "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/axis"], "attr": {"N": {"i": "3"}, "Tidx": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add/x", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1", "op": "ExpandDims", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1_const_axis"], "attr": {"Tdim": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "op": "Maximum", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Const", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1", "op": "Range", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/start", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/delta"], "attr": {"Tidx": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/StridedSlice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.log/Log", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/zeros_like", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/ones_like"], "attr": {"begin_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "end_mask": {"i": "0"}, "new_axis_mask": {"i": "0"}, "shrink_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape"], "attr": {"Tshape": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_1", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/StridedSlice", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add_1", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_3"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/GatherV2", "op": "GatherV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/strided_slice"], "attr": {"Tparams": {"type": "DT_FLOAT"}, "Taxis": {"type": "DT_INT32"}, "batch_dims": {"i": "0"}, "Tindices": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_4", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/GatherV2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_4"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/reshape/Shape", "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack", "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_1", "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_2"], "attr": {"end_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "begin_mask": {"i": "0"}, "shrink_axis_mask": {"i": "1"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/reshape/strided_slice", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/1", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/2", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/3"], "attr": {"T": {"type": "DT_INT32"}, "axis": {"i": "0"}, "N": {"i": "4"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_4", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/reshape/Reshape", "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "data_format": {"s": "TkhXQw=="}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer1/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "num_host_args": {"i": "0"}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "num_host_args": {"i": "0"}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "num_host_args": {"i": "0"}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean", "op": "Mean", "input": ["StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean/reduction_indices"], "attr": {"keep_dims": {"b": false}, "Tidx": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "Identity", "op": "Identity", "input": ["StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd", "op": "_FusedMatMul", "input": ["StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean", "StatefulPartitionedCall/yamnet_frames/dense/MatMul/ReadVariableOp", "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd/ReadVariableOp"], "device": "/device:CPU:0", "attr": {"leakyrelu_alpha": {"f": 0.2}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA=="]}}, "num_args": {"i": "1"}, "transpose_a": {"b": false}, "epsilon": {"f": 0.0}, "transpose_b": {"b": false}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/activation/Sigmoid", "op": "Sigmoid", "input": ["StatefulPartitionedCall/yamnet_frames/dense/BiasAdd"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "Identity_2", "op": "Identity", "input": ["StatefulPartitionedCall/yamnet_frames/activation/Sigmoid"], "attr": {"T": {"type": "DT_FLOAT"}}}], "library": {}, "versions": {"producer": 2474}}, "weightsManifest": [{"paths": ["group1-shard1of4.bin", "group1-shard2of4.bin", "group1-shard3of4.bin", "group1-shard4of4.bin"], "weights": [{"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/zeros_like", "shape": [2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/ones_like", "shape": [2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/start", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/delta", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_3", "shape": [1, 2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/strided_slice", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Const", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add/x", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape/shape_1", "shape": [0], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_step", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length", "shape": [], "dtype": "int32"}, {"name": "unknown_7", "shape": [512, 257], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/0_1", "shape": [2], "dtype": "int32"}, {"name": "unknown_5", "shape": [], "dtype": "int32"}, {"name": "unknown_4", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/zeros_like", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/ones_like", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/start", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/delta", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_2", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_3", "shape": [1, 5], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/strided_slice", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Const", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add/x", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape/shape_1", "shape": [0], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_step", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0/0", "shape": [], "dtype": "int32"}, {"name": "unknown_2", "shape": [], "dtype": "int32"}, {"name": "unknown_1", "shape": [], "dtype": "int32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv_recip", "shape": [], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_1", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_2", "shape": [1], "dtype": "int32"}, {"name": "unknown", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed", "shape": [3], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split/split_dim", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2/axis", "shape": [], "dtype": "int32"}, {"name": "unknown_3", "shape": [1, 400], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_1", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_2", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv/y", "shape": [], "dtype": "int32"}, {"name": "unknown_6", "shape": [512, 257], "dtype": "float32"}, {"name": "unknown_8", "shape": [257, 64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/y", "shape": [], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed", "shape": [3], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split/split_dim", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_1", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_2", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/2", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/3", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean/reduction_indices", "shape": [2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/MatMul/ReadVariableOp", "shape": [1024, 521], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd/ReadVariableOp", "shape": [521], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_weights", "shape": [3, 3, 1, 32], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_bn_offset", "shape": [32], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_weights", "shape": [3, 3, 32, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_bn_offset", "shape": [32], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_weights", "shape": [1, 1, 32, 64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_bn_offset", "shape": [64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_weights", "shape": [3, 3, 64, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_bn_offset", "shape": [64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_weights", "shape": [1, 1, 64, 128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_weights", "shape": [3, 3, 128, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_weights", "shape": [1, 1, 128, 128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_weights", "shape": [3, 3, 128, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_weights", "shape": [1, 1, 128, 256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_weights", "shape": [3, 3, 256, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_weights", "shape": [1, 1, 256, 256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_bn_offset", "shape": [1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_weights", "shape": [3, 3, 256, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_weights", "shape": [1, 1, 256, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_weights", "shape": [3, 3, 1024, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_bn_offset", "shape": [1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_weights", "shape": [1, 1, 1024, 1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_bn_offset", "shape": [1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings_const_axis", "shape": [], "dtype": "int32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1_const_axis", "shape": [], "dtype": "int32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1_const_axis", "shape": [], "dtype": "int32"}]}]} \ No newline at end of file diff --git a/fireworks_detect/static/browser-yamnet/yamnet_class_map.csv b/fireworks_detect/static/browser-yamnet/yamnet_class_map.csv new file mode 100644 index 0000000..9c07d81 --- /dev/null +++ b/fireworks_detect/static/browser-yamnet/yamnet_class_map.csv @@ -0,0 +1,522 @@ +index,mid,display_name +0,/m/09x0r,Speech +1,/m/0ytgt,"Child speech, kid speaking" +2,/m/01h8n0,Conversation +3,/m/02qldy,"Narration, monologue" +4,/m/0261r1,Babbling +5,/m/0brhx,Speech synthesizer +6,/m/07p6fty,Shout +7,/m/07q4ntr,Bellow +8,/m/07rwj3x,Whoop +9,/m/07sr1lc,Yell +10,/t/dd00135,Children shouting +11,/m/03qc9zr,Screaming +12,/m/02rtxlg,Whispering +13,/m/01j3sz,Laughter +14,/t/dd00001,Baby laughter +15,/m/07r660_,Giggle +16,/m/07s04w4,Snicker +17,/m/07sq110,Belly laugh +18,/m/07rgt08,"Chuckle, chortle" +19,/m/0463cq4,"Crying, sobbing" +20,/t/dd00002,"Baby cry, infant cry" +21,/m/07qz6j3,Whimper +22,/m/07qw_06,"Wail, moan" +23,/m/07plz5l,Sigh +24,/m/015lz1,Singing +25,/m/0l14jd,Choir +26,/m/01swy6,Yodeling +27,/m/02bk07,Chant +28,/m/01c194,Mantra +29,/t/dd00005,Child singing +30,/t/dd00006,Synthetic singing +31,/m/06bxc,Rapping +32,/m/02fxyj,Humming +33,/m/07s2xch,Groan +34,/m/07r4k75,Grunt +35,/m/01w250,Whistling +36,/m/0lyf6,Breathing +37,/m/07mzm6,Wheeze +38,/m/01d3sd,Snoring +39,/m/07s0dtb,Gasp +40,/m/07pyy8b,Pant +41,/m/07q0yl5,Snort +42,/m/01b_21,Cough +43,/m/0dl9sf8,Throat clearing +44,/m/01hsr_,Sneeze +45,/m/07ppn3j,Sniff +46,/m/06h7j,Run +47,/m/07qv_x_,Shuffle +48,/m/07pbtc8,"Walk, footsteps" +49,/m/03cczk,"Chewing, mastication" +50,/m/07pdhp0,Biting +51,/m/0939n_,Gargling +52,/m/01g90h,Stomach rumble +53,/m/03q5_w,"Burping, eructation" +54,/m/02p3nc,Hiccup +55,/m/02_nn,Fart +56,/m/0k65p,Hands +57,/m/025_jnm,Finger snapping +58,/m/0l15bq,Clapping +59,/m/01jg02,"Heart sounds, heartbeat" +60,/m/01jg1z,Heart murmur +61,/m/053hz1,Cheering +62,/m/028ght,Applause +63,/m/07rkbfh,Chatter +64,/m/03qtwd,Crowd +65,/m/07qfr4h,"Hubbub, speech noise, speech babble" +66,/t/dd00013,Children playing +67,/m/0jbk,Animal +68,/m/068hy,"Domestic animals, pets" +69,/m/0bt9lr,Dog +70,/m/05tny_,Bark +71,/m/07r_k2n,Yip +72,/m/07qf0zm,Howl +73,/m/07rc7d9,Bow-wow +74,/m/0ghcn6,Growling +75,/t/dd00136,Whimper (dog) +76,/m/01yrx,Cat +77,/m/02yds9,Purr +78,/m/07qrkrw,Meow +79,/m/07rjwbb,Hiss +80,/m/07r81j2,Caterwaul +81,/m/0ch8v,"Livestock, farm animals, working animals" +82,/m/03k3r,Horse +83,/m/07rv9rh,Clip-clop +84,/m/07q5rw0,"Neigh, whinny" +85,/m/01xq0k1,"Cattle, bovinae" +86,/m/07rpkh9,Moo +87,/m/0239kh,Cowbell +88,/m/068zj,Pig +89,/t/dd00018,Oink +90,/m/03fwl,Goat +91,/m/07q0h5t,Bleat +92,/m/07bgp,Sheep +93,/m/025rv6n,Fowl +94,/m/09b5t,"Chicken, rooster" +95,/m/07st89h,Cluck +96,/m/07qn5dc,"Crowing, cock-a-doodle-doo" +97,/m/01rd7k,Turkey +98,/m/07svc2k,Gobble +99,/m/09ddx,Duck +100,/m/07qdb04,Quack +101,/m/0dbvp,Goose +102,/m/07qwf61,Honk +103,/m/01280g,Wild animals +104,/m/0cdnk,"Roaring cats (lions, tigers)" +105,/m/04cvmfc,Roar +106,/m/015p6,Bird +107,/m/020bb7,"Bird vocalization, bird call, bird song" +108,/m/07pggtn,"Chirp, tweet" +109,/m/07sx8x_,Squawk +110,/m/0h0rv,"Pigeon, dove" +111,/m/07r_25d,Coo +112,/m/04s8yn,Crow +113,/m/07r5c2p,Caw +114,/m/09d5_,Owl +115,/m/07r_80w,Hoot +116,/m/05_wcq,"Bird flight, flapping wings" +117,/m/01z5f,"Canidae, dogs, wolves" +118,/m/06hps,"Rodents, rats, mice" +119,/m/04rmv,Mouse +120,/m/07r4gkf,Patter +121,/m/03vt0,Insect +122,/m/09xqv,Cricket +123,/m/09f96,Mosquito +124,/m/0h2mp,"Fly, housefly" +125,/m/07pjwq1,Buzz +126,/m/01h3n,"Bee, wasp, etc." +127,/m/09ld4,Frog +128,/m/07st88b,Croak +129,/m/078jl,Snake +130,/m/07qn4z3,Rattle +131,/m/032n05,Whale vocalization +132,/m/04rlf,Music +133,/m/04szw,Musical instrument +134,/m/0fx80y,Plucked string instrument +135,/m/0342h,Guitar +136,/m/02sgy,Electric guitar +137,/m/018vs,Bass guitar +138,/m/042v_gx,Acoustic guitar +139,/m/06w87,"Steel guitar, slide guitar" +140,/m/01glhc,Tapping (guitar technique) +141,/m/07s0s5r,Strum +142,/m/018j2,Banjo +143,/m/0jtg0,Sitar +144,/m/04rzd,Mandolin +145,/m/01bns_,Zither +146,/m/07xzm,Ukulele +147,/m/05148p4,Keyboard (musical) +148,/m/05r5c,Piano +149,/m/01s0ps,Electric piano +150,/m/013y1f,Organ +151,/m/03xq_f,Electronic organ +152,/m/03gvt,Hammond organ +153,/m/0l14qv,Synthesizer +154,/m/01v1d8,Sampler +155,/m/03q5t,Harpsichord +156,/m/0l14md,Percussion +157,/m/02hnl,Drum kit +158,/m/0cfdd,Drum machine +159,/m/026t6,Drum +160,/m/06rvn,Snare drum +161,/m/03t3fj,Rimshot +162,/m/02k_mr,Drum roll +163,/m/0bm02,Bass drum +164,/m/011k_j,Timpani +165,/m/01p970,Tabla +166,/m/01qbl,Cymbal +167,/m/03qtq,Hi-hat +168,/m/01sm1g,Wood block +169,/m/07brj,Tambourine +170,/m/05r5wn,Rattle (instrument) +171,/m/0xzly,Maraca +172,/m/0mbct,Gong +173,/m/016622,Tubular bells +174,/m/0j45pbj,Mallet percussion +175,/m/0dwsp,"Marimba, xylophone" +176,/m/0dwtp,Glockenspiel +177,/m/0dwt5,Vibraphone +178,/m/0l156b,Steelpan +179,/m/05pd6,Orchestra +180,/m/01kcd,Brass instrument +181,/m/0319l,French horn +182,/m/07gql,Trumpet +183,/m/07c6l,Trombone +184,/m/0l14_3,Bowed string instrument +185,/m/02qmj0d,String section +186,/m/07y_7,"Violin, fiddle" +187,/m/0d8_n,Pizzicato +188,/m/01xqw,Cello +189,/m/02fsn,Double bass +190,/m/085jw,"Wind instrument, woodwind instrument" +191,/m/0l14j_,Flute +192,/m/06ncr,Saxophone +193,/m/01wy6,Clarinet +194,/m/03m5k,Harp +195,/m/0395lw,Bell +196,/m/03w41f,Church bell +197,/m/027m70_,Jingle bell +198,/m/0gy1t2s,Bicycle bell +199,/m/07n_g,Tuning fork +200,/m/0f8s22,Chime +201,/m/026fgl,Wind chime +202,/m/0150b9,Change ringing (campanology) +203,/m/03qjg,Harmonica +204,/m/0mkg,Accordion +205,/m/0192l,Bagpipes +206,/m/02bxd,Didgeridoo +207,/m/0l14l2,Shofar +208,/m/07kc_,Theremin +209,/m/0l14t7,Singing bowl +210,/m/01hgjl,Scratching (performance technique) +211,/m/064t9,Pop music +212,/m/0glt670,Hip hop music +213,/m/02cz_7,Beatboxing +214,/m/06by7,Rock music +215,/m/03lty,Heavy metal +216,/m/05r6t,Punk rock +217,/m/0dls3,Grunge +218,/m/0dl5d,Progressive rock +219,/m/07sbbz2,Rock and roll +220,/m/05w3f,Psychedelic rock +221,/m/06j6l,Rhythm and blues +222,/m/0gywn,Soul music +223,/m/06cqb,Reggae +224,/m/01lyv,Country +225,/m/015y_n,Swing music +226,/m/0gg8l,Bluegrass +227,/m/02x8m,Funk +228,/m/02w4v,Folk music +229,/m/06j64v,Middle Eastern music +230,/m/03_d0,Jazz +231,/m/026z9,Disco +232,/m/0ggq0m,Classical music +233,/m/05lls,Opera +234,/m/02lkt,Electronic music +235,/m/03mb9,House music +236,/m/07gxw,Techno +237,/m/07s72n,Dubstep +238,/m/0283d,Drum and bass +239,/m/0m0jc,Electronica +240,/m/08cyft,Electronic dance music +241,/m/0fd3y,Ambient music +242,/m/07lnk,Trance music +243,/m/0g293,Music of Latin America +244,/m/0ln16,Salsa music +245,/m/0326g,Flamenco +246,/m/0155w,Blues +247,/m/05fw6t,Music for children +248,/m/02v2lh,New-age music +249,/m/0y4f8,Vocal music +250,/m/0z9c,A capella +251,/m/0164x2,Music of Africa +252,/m/0145m,Afrobeat +253,/m/02mscn,Christian music +254,/m/016cjb,Gospel music +255,/m/028sqc,Music of Asia +256,/m/015vgc,Carnatic music +257,/m/0dq0md,Music of Bollywood +258,/m/06rqw,Ska +259,/m/02p0sh1,Traditional music +260,/m/05rwpb,Independent music +261,/m/074ft,Song +262,/m/025td0t,Background music +263,/m/02cjck,Theme music +264,/m/03r5q_,Jingle (music) +265,/m/0l14gg,Soundtrack music +266,/m/07pkxdp,Lullaby +267,/m/01z7dr,Video game music +268,/m/0140xf,Christmas music +269,/m/0ggx5q,Dance music +270,/m/04wptg,Wedding music +271,/t/dd00031,Happy music +272,/t/dd00033,Sad music +273,/t/dd00034,Tender music +274,/t/dd00035,Exciting music +275,/t/dd00036,Angry music +276,/t/dd00037,Scary music +277,/m/03m9d0z,Wind +278,/m/09t49,Rustling leaves +279,/t/dd00092,Wind noise (microphone) +280,/m/0jb2l,Thunderstorm +281,/m/0ngt1,Thunder +282,/m/0838f,Water +283,/m/06mb1,Rain +284,/m/07r10fb,Raindrop +285,/t/dd00038,Rain on surface +286,/m/0j6m2,Stream +287,/m/0j2kx,Waterfall +288,/m/05kq4,Ocean +289,/m/034srq,"Waves, surf" +290,/m/06wzb,Steam +291,/m/07swgks,Gurgling +292,/m/02_41,Fire +293,/m/07pzfmf,Crackle +294,/m/07yv9,Vehicle +295,/m/019jd,"Boat, Water vehicle" +296,/m/0hsrw,"Sailboat, sailing ship" +297,/m/056ks2,"Rowboat, canoe, kayak" +298,/m/02rlv9,"Motorboat, speedboat" +299,/m/06q74,Ship +300,/m/012f08,Motor vehicle (road) +301,/m/0k4j,Car +302,/m/0912c9,"Vehicle horn, car horn, honking" +303,/m/07qv_d5,Toot +304,/m/02mfyn,Car alarm +305,/m/04gxbd,"Power windows, electric windows" +306,/m/07rknqz,Skidding +307,/m/0h9mv,Tire squeal +308,/t/dd00134,Car passing by +309,/m/0ltv,"Race car, auto racing" +310,/m/07r04,Truck +311,/m/0gvgw0,Air brake +312,/m/05x_td,"Air horn, truck horn" +313,/m/02rhddq,Reversing beeps +314,/m/03cl9h,"Ice cream truck, ice cream van" +315,/m/01bjv,Bus +316,/m/03j1ly,Emergency vehicle +317,/m/04qvtq,Police car (siren) +318,/m/012n7d,Ambulance (siren) +319,/m/012ndj,"Fire engine, fire truck (siren)" +320,/m/04_sv,Motorcycle +321,/m/0btp2,"Traffic noise, roadway noise" +322,/m/06d_3,Rail transport +323,/m/07jdr,Train +324,/m/04zmvq,Train whistle +325,/m/0284vy3,Train horn +326,/m/01g50p,"Railroad car, train wagon" +327,/t/dd00048,Train wheels squealing +328,/m/0195fx,"Subway, metro, underground" +329,/m/0k5j,Aircraft +330,/m/014yck,Aircraft engine +331,/m/04229,Jet engine +332,/m/02l6bg,"Propeller, airscrew" +333,/m/09ct_,Helicopter +334,/m/0cmf2,"Fixed-wing aircraft, airplane" +335,/m/0199g,Bicycle +336,/m/06_fw,Skateboard +337,/m/02mk9,Engine +338,/t/dd00065,Light engine (high frequency) +339,/m/08j51y,"Dental drill, dentist's drill" +340,/m/01yg9g,Lawn mower +341,/m/01j4z9,Chainsaw +342,/t/dd00066,Medium engine (mid frequency) +343,/t/dd00067,Heavy engine (low frequency) +344,/m/01h82_,Engine knocking +345,/t/dd00130,Engine starting +346,/m/07pb8fc,Idling +347,/m/07q2z82,"Accelerating, revving, vroom" +348,/m/02dgv,Door +349,/m/03wwcy,Doorbell +350,/m/07r67yg,Ding-dong +351,/m/02y_763,Sliding door +352,/m/07rjzl8,Slam +353,/m/07r4wb8,Knock +354,/m/07qcpgn,Tap +355,/m/07q6cd_,Squeak +356,/m/0642b4,Cupboard open or close +357,/m/0fqfqc,Drawer open or close +358,/m/04brg2,"Dishes, pots, and pans" +359,/m/023pjk,"Cutlery, silverware" +360,/m/07pn_8q,Chopping (food) +361,/m/0dxrf,Frying (food) +362,/m/0fx9l,Microwave oven +363,/m/02pjr4,Blender +364,/m/02jz0l,"Water tap, faucet" +365,/m/0130jx,Sink (filling or washing) +366,/m/03dnzn,Bathtub (filling or washing) +367,/m/03wvsk,Hair dryer +368,/m/01jt3m,Toilet flush +369,/m/012xff,Toothbrush +370,/m/04fgwm,Electric toothbrush +371,/m/0d31p,Vacuum cleaner +372,/m/01s0vc,Zipper (clothing) +373,/m/03v3yw,Keys jangling +374,/m/0242l,Coin (dropping) +375,/m/01lsmm,Scissors +376,/m/02g901,"Electric shaver, electric razor" +377,/m/05rj2,Shuffling cards +378,/m/0316dw,Typing +379,/m/0c2wf,Typewriter +380,/m/01m2v,Computer keyboard +381,/m/081rb,Writing +382,/m/07pp_mv,Alarm +383,/m/07cx4,Telephone +384,/m/07pp8cl,Telephone bell ringing +385,/m/01hnzm,Ringtone +386,/m/02c8p,"Telephone dialing, DTMF" +387,/m/015jpf,Dial tone +388,/m/01z47d,Busy signal +389,/m/046dlr,Alarm clock +390,/m/03kmc9,Siren +391,/m/0dgbq,Civil defense siren +392,/m/030rvx,Buzzer +393,/m/01y3hg,"Smoke detector, smoke alarm" +394,/m/0c3f7m,Fire alarm +395,/m/04fq5q,Foghorn +396,/m/0l156k,Whistle +397,/m/06hck5,Steam whistle +398,/t/dd00077,Mechanisms +399,/m/02bm9n,"Ratchet, pawl" +400,/m/01x3z,Clock +401,/m/07qjznt,Tick +402,/m/07qjznl,Tick-tock +403,/m/0l7xg,Gears +404,/m/05zc1,Pulleys +405,/m/0llzx,Sewing machine +406,/m/02x984l,Mechanical fan +407,/m/025wky1,Air conditioning +408,/m/024dl,Cash register +409,/m/01m4t,Printer +410,/m/0dv5r,Camera +411,/m/07bjf,Single-lens reflex camera +412,/m/07k1x,Tools +413,/m/03l9g,Hammer +414,/m/03p19w,Jackhammer +415,/m/01b82r,Sawing +416,/m/02p01q,Filing (rasp) +417,/m/023vsd,Sanding +418,/m/0_ksk,Power tool +419,/m/01d380,Drill +420,/m/014zdl,Explosion +421,/m/032s66,"Gunshot, gunfire" +422,/m/04zjc,Machine gun +423,/m/02z32qm,Fusillade +424,/m/0_1c,Artillery fire +425,/m/073cg4,Cap gun +426,/m/0g6b5,Fireworks +427,/g/122z_qxw,Firecracker +428,/m/07qsvvw,"Burst, pop" +429,/m/07pxg6y,Eruption +430,/m/07qqyl4,Boom +431,/m/083vt,Wood +432,/m/07pczhz,Chop +433,/m/07pl1bw,Splinter +434,/m/07qs1cx,Crack +435,/m/039jq,Glass +436,/m/07q7njn,"Chink, clink" +437,/m/07rn7sz,Shatter +438,/m/04k94,Liquid +439,/m/07rrlb6,"Splash, splatter" +440,/m/07p6mqd,Slosh +441,/m/07qlwh6,Squish +442,/m/07r5v4s,Drip +443,/m/07prgkl,Pour +444,/m/07pqc89,"Trickle, dribble" +445,/t/dd00088,Gush +446,/m/07p7b8y,Fill (with liquid) +447,/m/07qlf79,Spray +448,/m/07ptzwd,Pump (liquid) +449,/m/07ptfmf,Stir +450,/m/0dv3j,Boiling +451,/m/0790c,Sonar +452,/m/0dl83,Arrow +453,/m/07rqsjt,"Whoosh, swoosh, swish" +454,/m/07qnq_y,"Thump, thud" +455,/m/07rrh0c,Thunk +456,/m/0b_fwt,Electronic tuner +457,/m/02rr_,Effects unit +458,/m/07m2kt,Chorus effect +459,/m/018w8,Basketball bounce +460,/m/07pws3f,Bang +461,/m/07ryjzk,"Slap, smack" +462,/m/07rdhzs,"Whack, thwack" +463,/m/07pjjrj,"Smash, crash" +464,/m/07pc8lb,Breaking +465,/m/07pqn27,Bouncing +466,/m/07rbp7_,Whip +467,/m/07pyf11,Flap +468,/m/07qb_dv,Scratch +469,/m/07qv4k0,Scrape +470,/m/07pdjhy,Rub +471,/m/07s8j8t,Roll +472,/m/07plct2,Crushing +473,/t/dd00112,"Crumpling, crinkling" +474,/m/07qcx4z,Tearing +475,/m/02fs_r,"Beep, bleep" +476,/m/07qwdck,Ping +477,/m/07phxs1,Ding +478,/m/07rv4dm,Clang +479,/m/07s02z0,Squeal +480,/m/07qh7jl,Creak +481,/m/07qwyj0,Rustle +482,/m/07s34ls,Whir +483,/m/07qmpdm,Clatter +484,/m/07p9k1k,Sizzle +485,/m/07qc9xj,Clicking +486,/m/07rwm0c,Clickety-clack +487,/m/07phhsh,Rumble +488,/m/07qyrcz,Plop +489,/m/07qfgpx,"Jingle, tinkle" +490,/m/07rcgpl,Hum +491,/m/07p78v5,Zing +492,/t/dd00121,Boing +493,/m/07s12q4,Crunch +494,/m/028v0c,Silence +495,/m/01v_m0,Sine wave +496,/m/0b9m1,Harmonic +497,/m/0hdsk,Chirp tone +498,/m/0c1dj,Sound effect +499,/m/07pt_g0,Pulse +500,/t/dd00125,"Inside, small room" +501,/t/dd00126,"Inside, large room or hall" +502,/t/dd00127,"Inside, public space" +503,/t/dd00128,"Outside, urban or manmade" +504,/t/dd00129,"Outside, rural or natural" +505,/m/01b9nn,Reverberation +506,/m/01jnbd,Echo +507,/m/096m7z,Noise +508,/m/06_y0by,Environmental noise +509,/m/07rgkc5,Static +510,/m/06xkwv,Mains hum +511,/m/0g12c5,Distortion +512,/m/08p9q4,Sidetone +513,/m/07szfh9,Cacophony +514,/m/0chx_,White noise +515,/m/0cj0r,Pink noise +516,/m/07p_0gm,Throbbing +517,/m/01jwx6,Vibration +518,/m/07c52,Television +519,/m/06bz3,Radio +520,/m/07hvw1,Field recording diff --git a/fireworks_detect/static/browser-yamnet/yamnet_class_map.json b/fireworks_detect/static/browser-yamnet/yamnet_class_map.json new file mode 100644 index 0000000..ee5d3bc --- /dev/null +++ b/fireworks_detect/static/browser-yamnet/yamnet_class_map.json @@ -0,0 +1 @@ +["Speech", "Child speech, kid speaking", "Conversation", "Narration, monologue", "Babbling", "Speech synthesizer", "Shout", "Bellow", "Whoop", "Yell", "Children shouting", "Screaming", "Whispering", "Laughter", "Baby laughter", "Giggle", "Snicker", "Belly laugh", "Chuckle, chortle", "Crying, sobbing", "Baby cry, infant cry", "Whimper", "Wail, moan", "Sigh", "Singing", "Choir", "Yodeling", "Chant", "Mantra", "Child singing", "Synthetic singing", "Rapping", "Humming", "Groan", "Grunt", "Whistling", "Breathing", "Wheeze", "Snoring", "Gasp", "Pant", "Snort", "Cough", "Throat clearing", "Sneeze", "Sniff", "Run", "Shuffle", "Walk, footsteps", "Chewing, mastication", "Biting", "Gargling", "Stomach rumble", "Burping, eructation", "Hiccup", "Fart", "Hands", "Finger snapping", "Clapping", "Heart sounds, heartbeat", "Heart murmur", "Cheering", "Applause", "Chatter", "Crowd", "Hubbub, speech noise, speech babble", "Children playing", "Animal", "Domestic animals, pets", "Dog", "Bark", "Yip", "Howl", "Bow-wow", "Growling", "Whimper (dog)", "Cat", "Purr", "Meow", "Hiss", "Caterwaul", "Livestock, farm animals, working animals", "Horse", "Clip-clop", "Neigh, whinny", "Cattle, bovinae", "Moo", "Cowbell", "Pig", "Oink", "Goat", "Bleat", "Sheep", "Fowl", "Chicken, rooster", "Cluck", "Crowing, cock-a-doodle-doo", "Turkey", "Gobble", "Duck", "Quack", "Goose", "Honk", "Wild animals", "Roaring cats (lions, tigers)", "Roar", "Bird", "Bird vocalization, bird call, bird song", "Chirp, tweet", "Squawk", "Pigeon, dove", "Coo", "Crow", "Caw", "Owl", "Hoot", "Bird flight, flapping wings", "Canidae, dogs, wolves", "Rodents, rats, mice", "Mouse", "Patter", "Insect", "Cricket", "Mosquito", "Fly, housefly", "Buzz", "Bee, wasp, etc.", "Frog", "Croak", "Snake", "Rattle", "Whale vocalization", "Music", "Musical instrument", "Plucked string instrument", "Guitar", "Electric guitar", "Bass guitar", "Acoustic guitar", "Steel guitar, slide guitar", "Tapping (guitar technique)", "Strum", "Banjo", "Sitar", "Mandolin", "Zither", "Ukulele", "Keyboard (musical)", "Piano", "Electric piano", "Organ", "Electronic organ", "Hammond organ", "Synthesizer", "Sampler", "Harpsichord", "Percussion", "Drum kit", "Drum machine", "Drum", "Snare drum", "Rimshot", "Drum roll", "Bass drum", "Timpani", "Tabla", "Cymbal", "Hi-hat", "Wood block", "Tambourine", "Rattle (instrument)", "Maraca", "Gong", "Tubular bells", "Mallet percussion", "Marimba, xylophone", "Glockenspiel", "Vibraphone", "Steelpan", "Orchestra", "Brass instrument", "French horn", "Trumpet", "Trombone", "Bowed string instrument", "String section", "Violin, fiddle", "Pizzicato", "Cello", "Double bass", "Wind instrument, woodwind instrument", "Flute", "Saxophone", "Clarinet", "Harp", "Bell", "Church bell", "Jingle bell", "Bicycle bell", "Tuning fork", "Chime", "Wind chime", "Change ringing (campanology)", "Harmonica", "Accordion", "Bagpipes", "Didgeridoo", "Shofar", "Theremin", "Singing bowl", "Scratching (performance technique)", "Pop music", "Hip hop music", "Beatboxing", "Rock music", "Heavy metal", "Punk rock", "Grunge", "Progressive rock", "Rock and roll", "Psychedelic rock", "Rhythm and blues", "Soul music", "Reggae", "Country", "Swing music", "Bluegrass", "Funk", "Folk music", "Middle Eastern music", "Jazz", "Disco", "Classical music", "Opera", "Electronic music", "House music", "Techno", "Dubstep", "Drum and bass", "Electronica", "Electronic dance music", "Ambient music", "Trance music", "Music of Latin America", "Salsa music", "Flamenco", "Blues", "Music for children", "New-age music", "Vocal music", "A capella", "Music of Africa", "Afrobeat", "Christian music", "Gospel music", "Music of Asia", "Carnatic music", "Music of Bollywood", "Ska", "Traditional music", "Independent music", "Song", "Background music", "Theme music", "Jingle (music)", "Soundtrack music", "Lullaby", "Video game music", "Christmas music", "Dance music", "Wedding music", "Happy music", "Sad music", "Tender music", "Exciting music", "Angry music", "Scary music", "Wind", "Rustling leaves", "Wind noise (microphone)", "Thunderstorm", "Thunder", "Water", "Rain", "Raindrop", "Rain on surface", "Stream", "Waterfall", "Ocean", "Waves, surf", "Steam", "Gurgling", "Fire", "Crackle", "Vehicle", "Boat, Water vehicle", "Sailboat, sailing ship", "Rowboat, canoe, kayak", "Motorboat, speedboat", "Ship", "Motor vehicle (road)", "Car", "Vehicle horn, car horn, honking", "Toot", "Car alarm", "Power windows, electric windows", "Skidding", "Tire squeal", "Car passing by", "Race car, auto racing", "Truck", "Air brake", "Air horn, truck horn", "Reversing beeps", "Ice cream truck, ice cream van", "Bus", "Emergency vehicle", "Police car (siren)", "Ambulance (siren)", "Fire engine, fire truck (siren)", "Motorcycle", "Traffic noise, roadway noise", "Rail transport", "Train", "Train whistle", "Train horn", "Railroad car, train wagon", "Train wheels squealing", "Subway, metro, underground", "Aircraft", "Aircraft engine", "Jet engine", "Propeller, airscrew", "Helicopter", "Fixed-wing aircraft, airplane", "Bicycle", "Skateboard", "Engine", "Light engine (high frequency)", "Dental drill, dentist's drill", "Lawn mower", "Chainsaw", "Medium engine (mid frequency)", "Heavy engine (low frequency)", "Engine knocking", "Engine starting", "Idling", "Accelerating, revving, vroom", "Door", "Doorbell", "Ding-dong", "Sliding door", "Slam", "Knock", "Tap", "Squeak", "Cupboard open or close", "Drawer open or close", "Dishes, pots, and pans", "Cutlery, silverware", "Chopping (food)", "Frying (food)", "Microwave oven", "Blender", "Water tap, faucet", "Sink (filling or washing)", "Bathtub (filling or washing)", "Hair dryer", "Toilet flush", "Toothbrush", "Electric toothbrush", "Vacuum cleaner", "Zipper (clothing)", "Keys jangling", "Coin (dropping)", "Scissors", "Electric shaver, electric razor", "Shuffling cards", "Typing", "Typewriter", "Computer keyboard", "Writing", "Alarm", "Telephone", "Telephone bell ringing", "Ringtone", "Telephone dialing, DTMF", "Dial tone", "Busy signal", "Alarm clock", "Siren", "Civil defense siren", "Buzzer", "Smoke detector, smoke alarm", "Fire alarm", "Foghorn", "Whistle", "Steam whistle", "Mechanisms", "Ratchet, pawl", "Clock", "Tick", "Tick-tock", "Gears", "Pulleys", "Sewing machine", "Mechanical fan", "Air conditioning", "Cash register", "Printer", "Camera", "Single-lens reflex camera", "Tools", "Hammer", "Jackhammer", "Sawing", "Filing (rasp)", "Sanding", "Power tool", "Drill", "Explosion", "Gunshot, gunfire", "Machine gun", "Fusillade", "Artillery fire", "Cap gun", "Fireworks", "Firecracker", "Burst, pop", "Eruption", "Boom", "Wood", "Chop", "Splinter", "Crack", "Glass", "Chink, clink", "Shatter", "Liquid", "Splash, splatter", "Slosh", "Squish", "Drip", "Pour", "Trickle, dribble", "Gush", "Fill (with liquid)", "Spray", "Pump (liquid)", "Stir", "Boiling", "Sonar", "Arrow", "Whoosh, swoosh, swish", "Thump, thud", "Thunk", "Electronic tuner", "Effects unit", "Chorus effect", "Basketball bounce", "Bang", "Slap, smack", "Whack, thwack", "Smash, crash", "Breaking", "Bouncing", "Whip", "Flap", "Scratch", "Scrape", "Rub", "Roll", "Crushing", "Crumpling, crinkling", "Tearing", "Beep, bleep", "Ping", "Ding", "Clang", "Squeal", "Creak", "Rustle", "Whir", "Clatter", "Sizzle", "Clicking", "Clickety-clack", "Rumble", "Plop", "Jingle, tinkle", "Hum", "Zing", "Boing", "Crunch", "Silence", "Sine wave", "Harmonic", "Chirp tone", "Sound effect", "Pulse", "Inside, small room", "Inside, large room or hall", "Inside, public space", "Outside, urban or manmade", "Outside, rural or natural", "Reverberation", "Echo", "Noise", "Environmental noise", "Static", "Mains hum", "Distortion", "Sidetone", "Cacophony", "White noise", "Pink noise", "Throbbing", "Vibration", "Television", "Radio", "Field recording"] \ No newline at end of file diff --git a/fireworks_detect/templates/fireworks_detect/classification_result.html b/fireworks_detect/templates/fireworks_detect/classification_result.html index 0a7b695..dd32fe5 100644 --- a/fireworks_detect/templates/fireworks_detect/classification_result.html +++ b/fireworks_detect/templates/fireworks_detect/classification_result.html @@ -59,6 +59,11 @@ {% else %}

{% trans "No peak events were returned." %}

{% endif %} + {% if pending %} +
+
{% trans "Sent to Pending Review" %}

{% trans "An administrator will review this recording." %}

+
+ {% endif %} {% if submission_token %}
diff --git a/fireworks_detect/templates/fireworks_detect/includes/audio_upload_form.html b/fireworks_detect/templates/fireworks_detect/includes/audio_upload_form.html index 10fc48f..9010138 100644 --- a/fireworks_detect/templates/fireworks_detect/includes/audio_upload_form.html +++ b/fireworks_detect/templates/fireworks_detect/includes/audio_upload_form.html @@ -15,6 +15,14 @@
+

diff --git a/fireworks_detect/test_browser_processing.py b/fireworks_detect/test_browser_processing.py index a592875..6172ba0 100644 --- a/fireworks_detect/test_browser_processing.py +++ b/fireworks_detect/test_browser_processing.py @@ -37,6 +37,7 @@ class BrowserProcessingBetaTests(TestCase): self.assertEqual(response.json(), { "version": 1, "browser_processing_beta_enabled": False, "whitelist": [], "privacy_sensitive_speech": [], "thresholds": {}, + "model_version": "google-yamnet-1", "model_url": "", "class_map_url": "", }) self.assertIn("no-cache", response["Cache-Control"]) for url in (reverse("hello"), reverse("fireworks_detect:fireworks")): @@ -53,8 +54,9 @@ class BrowserProcessingBetaTests(TestCase): policy = self.client.get(reverse("fireworks_detect:browser_policy")).json() self.assertTrue(policy["browser_processing_beta_enabled"]) self.assertEqual(policy["whitelist"], ["Fireworks"]) - self.assertEqual(policy["privacy_sensitive_speech"], ["Speech"]) - self.assertEqual(policy["thresholds"], {}) + self.assertIn("Speech", policy["privacy_sensitive_speech"]) + self.assertEqual(policy["thresholds"], {"relevance": 0.5, "speech": 0.5}) + self.assertEqual(policy["model_url"], "/static/browser-yamnet/model.json") self.assertNotIn("token", json.dumps(policy).lower()) BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=False) self.assertFalse(self.client.get(reverse("fireworks_detect:browser_policy")).json()["browser_processing_beta_enabled"]) @@ -99,3 +101,50 @@ class BrowserProcessingBetaTests(TestCase): }) self.assertEqual(response.status_code, 200) self.assertEqual(PendingEvent.objects.get().classifier_response, payload) + + @patch("fireworks_detect.views.urlopen") + def test_speech_override_runs_server_classifier_and_enters_pending(self, urlopen): + reply = MagicMock() + reply.read.return_value = b'{"predictions": [{"class": "Speech", "score": 0.9}]}' + urlopen.return_value.__enter__.return_value = reply + BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=True) + with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root), patch.object( + PendingEvent._meta.get_field("audio_file"), "storage", FileSystemStorage(location=media_root) + ): + response = self.client.post(reverse("fireworks_detect:classify_upload"), { + "audio": SimpleUploadedFile("speech.wav", b"RIFF0000WAVEdata", content_type="audio/wav"), + "browser_processing_metadata": json.dumps({ + "browser_processing_used": True, "browser_processing_version": 1, + "browser_gate_result": "speech_only", "browser_override": True, + }), + }) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "review-submission") + pending = PendingEvent.objects.get() + self.assertEqual(pending.classifier_response, {"predictions": [{"class": "Speech", "score": 0.9}]}) + self.assertEqual(urlopen.call_count, 1) + self.assertNotIn(b"speech_only", urlopen.call_args.args[0].data) + + @patch("fireworks_detect.views.urlopen") + def test_no_match_override_enters_pending_and_forged_whitelist_does_not_skip_classifier(self, urlopen): + reply = MagicMock() + reply.read.return_value = b'{"predictions": [{"class": "Music", "score": 0.9}]}' + urlopen.return_value.__enter__.return_value = reply + BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=True) + with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root), patch.object( + PendingEvent._meta.get_field("audio_file"), "storage", FileSystemStorage(location=media_root) + ): + response = self.client.post(reverse("fireworks_detect:classify_upload"), { + "audio": SimpleUploadedFile("music.wav", b"RIFF0000WAVEdata", content_type="audio/wav"), + "browser_processing_metadata": '{"browser_gate_result":"no_match","browser_override":true}', + }) + self.assertEqual(response.status_code, 200) + self.assertEqual(PendingEvent.objects.count(), 1) + response = self.client.post(reverse("fireworks_detect:classify_upload"), { + "audio": SimpleUploadedFile("sample.wav", b"RIFF0000WAVEdata", content_type="audio/wav"), + "browser_processing_metadata": '{"browser_gate_result":"whitelist_match","browser_override":false}', + }) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "Music") + self.assertEqual(PendingEvent.objects.count(), 1) + self.assertEqual(urlopen.call_count, 2) diff --git a/fireworks_detect/views.py b/fireworks_detect/views.py index ee67f05..06537c7 100644 --- a/fireworks_detect/views.py +++ b/fireworks_detect/views.py @@ -22,7 +22,7 @@ from django.views.decorators.http import require_http_methods from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution from .browser_policy import advisory_browser_metadata, browser_config, browser_policy -from .models import ClassificationRule, Event, PendingEvent, Sensor +from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor CLASSIFIER_URL = "http://192.168.1.122:5000/classify" @@ -286,7 +286,23 @@ def classify_upload(request): # Keep the raw payload in this request flow; this is the future hand-off point # for saving the upload and its classification to a database or queue. context = _classification_context(payload) - context["submission_token"] = signing.dumps(payload, salt="fireworks_detect.classification") + override = ( + BrowserProcessingSettings.enabled() + and metadata.get("browser_override") is True + and metadata.get("browser_gate_result") in {"speech_only", "no_match"} + ) + if override: + # The browser gate is advisory. Always classify server-side first, then + # force this explicit override into Pending Review regardless of scores. + pending = PendingEvent.objects.create( + audio_file=uploaded_file, + original_filename=uploaded_file.name, + classifier_response=payload, + ) + context["pending"] = pending + logger.info("Browser override sent to Pending Review: %s", pending.pk) + else: + context["submission_token"] = signing.dumps(payload, salt="fireworks_detect.classification") return render(request, "fireworks_detect/classification_result.html", context) diff --git a/frontend/src/scripts/audio-preprocessor.js b/frontend/src/scripts/audio-preprocessor.js new file mode 100644 index 0000000..6e1a7c2 --- /dev/null +++ b/frontend/src/scripts/audio-preprocessor.js @@ -0,0 +1,31 @@ +const RATE = 16000; + +export class AudioPreprocessor { + static async prepare(file, { signal } = {}) { + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + console.log("[BoomCast][YAMNet] Preparing local classification."); + const AudioContextClass = window.AudioContext || window.webkitAudioContext; + if (!AudioContextClass || !(window.OfflineAudioContext || window.webkitOfflineAudioContext)) throw new Error("Browser audio decoding unavailable"); + const context = new AudioContextClass(); + try { + const decoded = await context.decodeAudioData(await file.arrayBuffer()); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + if (!decoded.duration || !Number.isFinite(decoded.duration)) throw new Error("Invalid audio duration"); + const OfflineContextClass = window.OfflineAudioContext || window.webkitOfflineAudioContext; + const offline = new OfflineContextClass(1, Math.ceil(decoded.duration * RATE), RATE); + const source = offline.createBufferSource(); + source.buffer = decoded; + source.connect(offline.destination); + source.start(); + const rendered = await offline.startRendering(); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + const waveform = rendered.getChannelData(0).slice(); + console.log("[BoomCast][YAMNet] Waveform prepared.", { + sampleRate: RATE, samples: waveform.length, durationSeconds: waveform.length / RATE, + }); + return waveform; + } finally { + await context.close().catch(() => {}); + } + } +} diff --git a/frontend/src/scripts/audio-upload.js b/frontend/src/scripts/audio-upload.js index b90ded7..13a4b01 100644 --- a/frontend/src/scripts/audio-upload.js +++ b/frontend/src/scripts/audio-upload.js @@ -12,6 +12,11 @@ if (form) { const submit = form.querySelector('button[type="submit"]'); const cancel = form.querySelector(".upload-cancel"); const results = form.querySelector("#classification-results"); + const gatePanel = form.querySelector("#browser-gate"); + const gateTitle = form.querySelector("#browser-gate-title"); + const gateMessage = form.querySelector("#browser-gate-message"); + const gateChoose = form.querySelector("#browser-gate-choose"); + const gateOverride = form.querySelector("#browser-gate-override"); const status = document.querySelector("#upload-status"); const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)"); const states = ["idle", "file-selected", "uploading", "processing", "success", "error", "cancelled"]; @@ -23,8 +28,9 @@ if (form) { let selectionId = 0; let selectionController = null; let selectedResult = null; - let extractionPending = false; - let extractionFailed = false; + let preparationPending = false; + let preparationFailed = false; + let gateBlocked = false; const browserProcessor = new BrowserSubmissionProcessor(); if (!browserProcessor.isEnabled()) { console.log("[BoomCast][BrowserBeta] Feature disabled; using legacy submission flow."); @@ -130,41 +136,68 @@ if (form) { selectionController?.abort(); selectionController = null; selectedResult = null; - extractionPending = false; - extractionFailed = false; + preparationPending = false; + preparationFailed = false; + gateBlocked = false; + gatePanel.hidden = true; showFile(file); if (!busy) { submit.disabled = false; cancel.hidden = true; } - if (!file || !browserProcessor.isEnabled() || !BrowserSubmissionProcessor.isVideo(file)) return; + if (!file || !browserProcessor.canProcess(file)) return; const id = selectionId; const controller = new AbortController(); selectionController = controller; - extractionPending = true; + preparationPending = true; submit.disabled = true; cancel.hidden = false; - status.textContent = t.extractingAudio || "Extracting audio from video…"; + status.textContent = BrowserSubmissionProcessor.isVideo(file) + ? (t.extractingAudio || "Extracting audio from video…") + : (t.preparingRecording || "Preparing recording…"); browserProcessor.prepare(file, { signal: controller.signal, onState: (state) => { - if (id === selectionId) console.log("[BoomCast][FFmpeg] State:", state); + if (id !== selectionId) return; + status.textContent = state === "checking" ? (t.checkingRecording || "Checking recording…") + : (t.extractingAudio || "Extracting audio from video…"); } }).then((result) => { if (id !== selectionId || controller.signal.aborted) return; - selectedResult = result; - extractionPending = false; - submit.disabled = false; + preparationPending = false; cancel.hidden = true; - status.textContent = result.file === file - ? (t.videoExtractionUnavailable || "Video processing is unavailable. Please choose an audio recording.") - : (t.onlyAudioSent || "Audio extracted on this device. Only audio will be sent to BoomCast."); - extractionFailed = result.file === file; - if (extractionFailed) submit.disabled = true; + if (BrowserSubmissionProcessor.isVideo(file) && result.file === file) { + preparationFailed = true; + submit.disabled = true; + status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording."; + return; + } + selectedResult = result; + gateBlocked = result.gate === "speech_only" || result.gate === "no_match"; + if (gateBlocked) { + gateTitle.textContent = result.gate === "speech_only" + ? (t.speechGateTitle || "This recording appears to contain speech, but no relevant sound was detected.") + : (t.irrelevantGateTitle || "No relevant sound was detected."); + gateMessage.textContent = result.gate === "speech_only" + ? (t.speechGateMessage || "To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review.") + : (t.irrelevantGateMessage || "BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review."); + gatePanel.hidden = false; + submit.disabled = true; + status.textContent = (t.gateChooseMessage || "Recording checked. Choose another recording or submit for manual review."); + } else { + submit.disabled = false; + status.textContent = BrowserSubmissionProcessor.isVideo(file) + ? (t.videoAudioOnly || "Video processed on this device. Only extracted audio will be sent if you submit.") + : (t.readyToSubmit || "Ready to submit."); + } }).catch((error) => { if (id !== selectionId) return; - console.error("[BoomCast][FFmpeg] Falling back safely.", error); - extractionPending = false; - extractionFailed = true; - submit.disabled = true; + console.error("[BoomCast][BrowserBeta] Preparation failed:", error); + preparationPending = false; cancel.hidden = true; - status.textContent = controller.signal.aborted - ? (t.extractionCancelled || "Audio extraction cancelled. Choose a recording to continue.") - : (t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording."); + if (BrowserSubmissionProcessor.isVideo(file)) { + preparationFailed = true; + submit.disabled = true; + status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording."; + } else { + selectedResult = { file, metadata: null, gate: "unavailable" }; + submit.disabled = false; + status.textContent = t.readyToSubmit || "Ready to submit."; + } }); } @@ -184,6 +217,22 @@ if (form) { }); function startUpload(file, metadata = null) { + // HTMX's later Pending action also reads the native file input. Replace a + // video with its extracted WAV so no subsequent form action can send video. + if (fileInput.files[0] !== file) { + try { + const transfer = new DataTransfer(); + transfer.items.add(file); + fileInput.files = transfer.files; + if (fileInput.files[0] !== file) throw new Error("Prepared audio could not replace video in form"); + } catch (error) { + console.error("[BoomCast][BrowserBeta] Could not secure native form upload:", error); + preparationFailed = true; + submit.disabled = true; + status.textContent = (t.secureVideoFailed || "Could not prepare this video for upload. Please choose an audio recording."); + return; + } + } const formData = new FormData(form); formData.set("audio", file); if (metadata) formData.set("browser_processing_metadata", JSON.stringify(metadata)); @@ -226,59 +275,36 @@ if (form) { form.addEventListener("submit", (event) => { event.preventDefault(); event.stopImmediatePropagation(); - if (busy || preparing || extractionPending || extractionFailed) return; + if (busy || preparationPending || preparationFailed || gateBlocked) return; if (!form.reportValidity()) return; const file = fileInput.files[0]; if (!file) return; - if (selectedResult && BrowserSubmissionProcessor.isVideo(file)) { - startUpload(selectedResult.file, selectedResult.metadata); - return; - } - if (!browserProcessor.isEnabled()) { - startUpload(file); - return; - } - const id = selectionId; - preparing = true; - submit.disabled = true; - status.textContent = t.preparingRecording || "Preparing recording…"; - browserProcessor.prepare(file).then(({ file: preparedFile, metadata }) => { - preparing = false; - submit.disabled = false; - if (fileInput.files[0] !== file || selectionId !== id) return; - if (BrowserSubmissionProcessor.isVideo(file) && preparedFile === file) { - extractionFailed = true; - submit.disabled = true; - status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording."; - return; - } - startUpload(preparedFile || file, metadata); - }).catch((error) => { - console.error("[BoomCast][BrowserBeta] Initialisation failed:", error); - browserProcessor.cleanup(); - console.log("[BoomCast][BrowserBeta] Restoring legacy submission flow."); - preparing = false; - submit.disabled = false; - if (fileInput.files[0] !== file || selectionId !== id) return; - if (BrowserSubmissionProcessor.isVideo(file)) { - extractionFailed = true; - submit.disabled = true; - status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording."; - return; - } - if (fileInput.files[0] === file && selectionId === id) startUpload(file); - }); + if (selectedResult) { startUpload(selectedResult.file, selectedResult.metadata); return; } + if (!browserProcessor.isEnabled()) { startUpload(file); return; } + // Unknown types retain the existing server flow. + startUpload(file); }, true); + gateChoose.addEventListener("click", () => fileInput.click()); + gateOverride.addEventListener("click", () => { + if (!gateBlocked || !selectedResult || busy || preparationPending) return; + console.warn("[BoomCast][Gate] User explicitly overrode local gate."); + console.log("[BoomCast][Gate] Submission will enter manual review."); + const metadata = { ...selectedResult.metadata, browser_override: true }; + selectedResult.metadata = metadata; + gateBlocked = false; + gatePanel.hidden = true; + startUpload(selectedResult.file, metadata); + }); cancel.addEventListener("click", () => { - if (extractionPending) { + if (preparationPending) { selectionController?.abort(); selectionId += 1; - extractionPending = false; - extractionFailed = true; + preparationPending = false; + preparationFailed = true; submit.disabled = true; cancel.hidden = true; - status.textContent = t.extractionCancelled || "Audio extraction cancelled. Choose a recording to continue."; + status.textContent = t.extractionCancelled || (t.preparationCancelled || "Preparation cancelled. Choose a recording to continue."); } else request?.abort(); }); window.addEventListener("pageshow", (event) => { @@ -287,8 +313,10 @@ if (form) { selectionController?.abort(); selectionId += 1; selectedResult = null; - extractionPending = false; - extractionFailed = false; + preparationPending = false; + preparationFailed = false; + gateBlocked = false; + gatePanel.hidden = true; submit.disabled = false; fileInput.value = ""; results.replaceChildren(); diff --git a/frontend/src/scripts/browser-submission-gate.js b/frontend/src/scripts/browser-submission-gate.js new file mode 100644 index 0000000..0970156 --- /dev/null +++ b/frontend/src/scripts/browser-submission-gate.js @@ -0,0 +1,17 @@ +export class BrowserSubmissionGate { + static evaluate(predictions, policy) { + console.log("[BoomCast][Gate] Evaluating browser classification."); + const relevant = new Set((policy.whitelist || []).map((name) => name.toLowerCase())); + const speechNames = new Set((policy.privacy_sensitive_speech || []).map((name) => name.toLowerCase())); + const matchThreshold = Number(policy.thresholds?.relevance ?? 0.5); + const speechThreshold = Number(policy.thresholds?.speech ?? 0.5); + const matches = predictions.filter((item) => relevant.has(item.class.toLowerCase()) && item.score >= matchThreshold); + const speechDetected = predictions.some((item) => speechNames.has(item.class.toLowerCase()) && item.score >= speechThreshold); + console.log("[BoomCast][Gate] Relevant whitelist matches:", matches); + console.log("[BoomCast][Gate] Speech detected:", speechDetected); + const result = matches.length ? "whitelist_match" : speechDetected ? "speech_only" : "no_match"; + console.log(`[BoomCast][Gate] Decision: ${result.toUpperCase()}`); + if (result !== "whitelist_match") console.log("[BoomCast][Gate] Automatic upload suppressed."); + return { result, speechDetected, matches }; + } +} diff --git a/frontend/src/scripts/browser-submission-processor.js b/frontend/src/scripts/browser-submission-processor.js index af4de8f..8922a9f 100644 --- a/frontend/src/scripts/browser-submission-processor.js +++ b/frontend/src/scripts/browser-submission-processor.js @@ -3,82 +3,104 @@ const PREFIX = "[BoomCast][BrowserBeta]"; export function readBrowserProcessingConfig() { const element = document.querySelector("#boomcast-browser-config"); if (!element) return { browserProcessingBeta: false }; - try { - return JSON.parse(element.textContent); - } catch (error) { + try { return JSON.parse(element.textContent); } + catch (error) { console.error(`${PREFIX} Configuration unavailable:`, error); return { browserProcessingBeta: false }; } } export class BrowserSubmissionProcessor { - constructor(config = readBrowserProcessingConfig(), extractVideo = null) { + constructor(config = readBrowserProcessingConfig(), extractVideo = null, dependencies = {}) { this.config = config; this.extractVideo = extractVideo; + this.dependencies = dependencies; } - isEnabled() { - return this.config.browserProcessingBeta === true; - } + isEnabled() { return this.config.browserProcessingBeta === true; } canProcess(file) { - return this.isEnabled() && Boolean(file) && /^(audio|video)\//.test(file.type); + return this.isEnabled() && Boolean(file) && (BrowserSubmissionProcessor.isAudio(file) || BrowserSubmissionProcessor.isVideo(file)); + } + + static isAudio(file) { + return Boolean(file) && (file.type.startsWith("audio/") || (!file.type && /\.(aac|aif|aiff|flac|m4a|mp3|ogg|opus|wav|weba)$/i.test(file.name || ""))); } static isVideo(file) { return Boolean(file) && (file.type.startsWith("video/") || (!file.type && /\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(file.name || ""))); } - async prepare(file, { signal, onState } = {}) { - if (!this.isEnabled()) return { file, metadata: null }; + async prepare(file, { signal, onState = () => {} } = {}) { + if (!this.canProcess(file)) return { file, metadata: null, gate: "unavailable" }; console.log(`${PREFIX} Initialising beta submission pipeline.`); console.log(`${PREFIX} File selected:`, { type: file?.type || "", size: file?.size || 0 }); - if (!this.canProcess(file) && !BrowserSubmissionProcessor.isVideo(file)) { - console.log(`${PREFIX} Browser preprocessing unavailable; falling back.`); - return { file, metadata: null }; - } - let policyTimeout; + const video = BrowserSubmissionProcessor.isVideo(file); + const controller = new AbortController(); + const abort = () => controller.abort(); + signal?.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(() => controller.abort(), 5000); + let policy; try { - const controller = new AbortController(); - policyTimeout = setTimeout(() => controller.abort(), 5000); const response = await fetch(this.config.policyUrl, { cache: "no-store", credentials: "same-origin", signal: controller.signal, }); if (!response.ok) throw new Error(`Policy HTTP ${response.status}`); - const policy = await response.json(); + policy = await response.json(); if (!policy.browser_processing_beta_enabled || policy.version !== this.config.policyVersion) { console.log(`${PREFIX} Browser beta disabled or policy changed; using legacy submission flow.`); - return { file, metadata: null }; + return { file, metadata: null, gate: "unavailable" }; } - if (BrowserSubmissionProcessor.isVideo(file)) { - const extract = this.extractVideo || (await import("./ffmpeg-video-extractor.js")).extractVideoAudio; - const wav = await extract(file, { signal, onState }); - return { file: wav, metadata: { browser_processing_used: true, browser_processing_version: policy.version, browser_gate_result: "unavailable", browser_override: false } }; - } - // Audio continues through the existing submission path. - console.log(`${PREFIX} Browser processing shell ready; using original recording.`); - return { - file, - metadata: { - browser_processing_used: false, - browser_processing_version: policy.version, - browser_gate_result: "unavailable", - browser_override: false, - }, - }; } catch (error) { - console.error(`${PREFIX} Initialisation failed:`, error); - this.cleanup(); - if (BrowserSubmissionProcessor.isVideo(file)) throw error; - console.log(`${PREFIX} Restoring legacy submission flow.`); - return { file, metadata: null }; + if (signal?.aborted) throw error; + console.error(`${PREFIX} Policy unavailable:`, error); + if (video) throw error; + return { file, metadata: null, gate: "unavailable" }; } finally { - clearTimeout(policyTimeout); + clearTimeout(timeout); + signal?.removeEventListener("abort", abort); + } + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + let preparedFile = file; + if (video) { + const extract = this.extractVideo || (await import("./ffmpeg-video-extractor.js")).extractVideoAudio; + preparedFile = await extract(file, { signal, onState }); + } + const metadata = { + browser_processing_used: video, + browser_processing_version: policy.version, + browser_gate_result: "unavailable", + browser_override: false, + }; + try { + onState("checking"); + const prepareAudio = this.dependencies.prepareAudio || (await import("./audio-preprocessor.js")).AudioPreprocessor.prepare; + let waveform = await prepareAudio(preparedFile, { signal }); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + try { + const classify = this.dependencies.classify || (await import("./browser-yamnet-classifier.js")).BrowserYamnetClassifier.classify; + const predictions = await classify(waveform, { + modelUrl: policy.model_url, classMapUrl: policy.class_map_url, signal, + }); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + const evaluate = this.dependencies.evaluate || (await import("./browser-submission-gate.js")).BrowserSubmissionGate.evaluate; + const decision = evaluate(predictions, policy); + metadata.browser_processing_used = true; + metadata.browser_gate_result = decision.result; + metadata.browser_speech_detected = decision.speechDetected; + return { file: preparedFile, metadata, gate: decision.result, predictions: predictions.slice(0, 5) }; + } finally { + waveform = null; + console.log("[BoomCast][Cleanup] Releasing waveform buffers."); + } + } catch (error) { + if (signal?.aborted) throw error; + console.error("[BoomCast][YAMNet] Local classification unavailable:", error); + console.log("[BoomCast][Gate] Falling back to server classification."); + metadata.browser_gate_result = "unavailable"; + return { file: preparedFile, metadata, gate: "unavailable" }; } } - cleanup() { - // Future passes can release workers, object URLs, and model tensors here. - console.log("[BoomCast][Cleanup] Browser beta resources released."); - } + cleanup() { console.log("[BoomCast][Cleanup] Browser beta resources released."); } } diff --git a/frontend/src/scripts/browser-yamnet-classifier.js b/frontend/src/scripts/browser-yamnet-classifier.js new file mode 100644 index 0000000..d655575 --- /dev/null +++ b/frontend/src/scripts/browser-yamnet-classifier.js @@ -0,0 +1,70 @@ +const PREFIX = "[BoomCast][YAMNet]"; + +export class BrowserYamnetClassifier { + static async classify(waveform, { modelUrl, classMapUrl, signal, loadTensorFlow } = {}) { + let tf; + let model; + let input; + let output; + const started = performance.now(); + try { + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + console.log(`${PREFIX} Lazy-loading TensorFlow.js.`); + tf = loadTensorFlow ? await loadTensorFlow() : await import("@tensorflow/tfjs"); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + console.log(`${PREFIX} TensorFlow.js loaded.`); + await tf.ready(); + console.log(`${PREFIX} Backend:`, tf.getBackend()); + console.log(`${PREFIX} Loading model.`); + const [loaded, mappingResponse] = await Promise.all([ + tf.loadGraphModel(modelUrl), + fetch(classMapUrl, { cache: "force-cache", signal }), + ]); + model = loaded; + if (!mappingResponse.ok) throw new Error("YAMNet class map unavailable"); + const classMap = await mappingResponse.json(); + if (!Array.isArray(classMap) || classMap.length !== 521) throw new Error("Invalid YAMNet class map"); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + console.log(`${PREFIX} Model ready.`); + // YAMNet needs at least one 0.96 s patch, including STFT padding. + const samples = waveform.length < 15600 ? Float32Array.from({ length: 15600 }, (_, i) => waveform[i] || 0) : waveform; + input = tf.tensor1d(samples, "float32"); + console.log(`${PREFIX} Starting inference.`); + const result = await model.executeAsync(input); + output = Array.isArray(result) ? result : [result]; + const scores = output.find((tensor) => tensor.shape.length === 2 && tensor.shape[1] === classMap.length); + if (!scores) throw new Error("YAMNet score output unavailable"); + const values = await scores.data(); + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); + const frames = scores.shape[0]; + const predictions = classMap.map((name, index) => { + let score = -1; + let frame = 0; + for (let row = 0; row < frames; row += 1) { + const value = values[row * classMap.length + index]; + if (value > score) { score = value; frame = row; } + } + return { class: name, score, frame, timeSeconds: Number((frame * 0.48).toFixed(2)) }; + }); + predictions.sort((a, b) => b.score - a.score); + console.log(`${PREFIX} Inference completed in`, Math.round(performance.now() - started), "ms."); + console.groupCollapsed(`${PREFIX} Top local predictions`); + console.table(predictions.slice(0, 10)); + console.groupEnd(); + return predictions; + } catch (error) { + console.error(`${PREFIX} Local inference failed:`, error); + throw error; + } finally { + if (tf) console.log(`${PREFIX} TensorFlow memory before cleanup:`, tf.memory()); + console.log("[BoomCast][Cleanup] Disposing YAMNet tensors."); + input?.dispose(); + output?.forEach((tensor) => tensor?.dispose()); + console.log("[BoomCast][Cleanup] Disposing browser YAMNet model."); + model?.dispose(); + console.log("[BoomCast][Cleanup] Releasing waveform buffers."); + if (tf) console.log(`${PREFIX} TensorFlow memory after cleanup:`, tf.memory()); + console.log("[BoomCast][Cleanup] Browser classification cleanup complete."); + } + } +} diff --git a/frontend/src/styles/pages/fireworks-home.css b/frontend/src/styles/pages/fireworks-home.css index e0819e8..87fb92e 100644 --- a/frontend/src/styles/pages/fireworks-home.css +++ b/frontend/src/styles/pages/fireworks-home.css @@ -509,3 +509,9 @@ transition-duration: .01ms !important; } } + +.browser-gate { margin: 1rem 0; padding: 1rem; border: 1px solid #e5bb7a; border-radius: .75rem; background: #4d392950; } +.browser-gate[hidden] { display: none; } +.browser-gate p { margin: .45rem 0 1rem; } +.browser-gate-actions { display: flex; gap: .65rem; flex-wrap: wrap; } +.browser-gate-actions button { cursor: pointer; } diff --git a/frontend/tests/browser-submission-gate.test.mjs b/frontend/tests/browser-submission-gate.test.mjs new file mode 100644 index 0000000..6627df7 --- /dev/null +++ b/frontend/tests/browser-submission-gate.test.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { BrowserSubmissionGate } from "../src/scripts/browser-submission-gate.js"; +import { BrowserSubmissionProcessor } from "../src/scripts/browser-submission-processor.js"; + +const policy = { whitelist: ["Fireworks"], privacy_sensitive_speech: ["Speech"], thresholds: { relevance: .5, speech: .5 } }; + +test("whitelist match allows normal submission even when speech is present", () => { + const decision = BrowserSubmissionGate.evaluate([{ class: "Fireworks", score: .8 }, { class: "Speech", score: .9 }], policy); + assert.equal(decision.result, "whitelist_match"); + assert.equal(decision.speechDetected, true); +}); + +test("speech without relevance and irrelevant audio require explicit override", () => { + assert.equal(BrowserSubmissionGate.evaluate([{ class: "Speech", score: .9 }], policy).result, "speech_only"); + assert.equal(BrowserSubmissionGate.evaluate([{ class: "Music", score: .9 }], policy).result, "no_match"); +}); + +test("audio and video-derived WAV use the same gate; audio never calls FFmpeg", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) }); + let extractionCalls = 0; + let classificationCalls = 0; + const processor = new BrowserSubmissionProcessor( + { browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, + async () => { extractionCalls += 1; return new File(["wav"], "clip.wav", { type: "audio/wav" }); }, + { prepareAudio: async () => new Float32Array(16000), classify: async () => { classificationCalls += 1; return [{ class: "Speech", score: .9 }]; } }, + ); + try { + assert.equal((await processor.prepare(new File(["audio"], "audio.wav", { type: "audio/wav" }))).gate, "speech_only"); + assert.equal(extractionCalls, 0); + assert.equal((await processor.prepare(new File(["video"], "clip.mp4", { type: "video/mp4" }))).gate, "speech_only"); + assert.equal(extractionCalls, 1); + assert.equal(classificationCalls, 2); + } finally { globalThis.fetch = originalFetch; } +}); + +test("local classifier failure restores ordinary server upload", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) }); + const processor = new BrowserSubmissionProcessor( + { browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null, + { prepareAudio: async () => new Float32Array(16000), classify: async () => { throw new Error("offline"); } }, + ); + const audio = new File(["audio"], "audio.wav", { type: "audio/wav" }); + try { + const result = await processor.prepare(audio); + assert.equal(result.file, audio); + assert.equal(result.gate, "unavailable"); + } finally { globalThis.fetch = originalFetch; } +}); + +test("aborted classification never yields a gate decision", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) }); + const controller = new AbortController(); + const processor = new BrowserSubmissionProcessor( + { browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null, + { prepareAudio: async () => new Float32Array(16000), classify: async () => { controller.abort(); return [{ class: "Fireworks", score: .9 }]; } }, + ); + try { + await assert.rejects(processor.prepare(new File(["audio"], "audio.wav", { type: "audio/wav" }), { signal: controller.signal })); + } finally { globalThis.fetch = originalFetch; } +}); diff --git a/frontend/tests/browser-submission-processor.test.mjs b/frontend/tests/browser-submission-processor.test.mjs index f44194a..0b677ee 100644 --- a/frontend/tests/browser-submission-processor.test.mjs +++ b/frontend/tests/browser-submission-processor.test.mjs @@ -12,7 +12,7 @@ test("disabled beta returns the original file without loading policy", async () const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: false }); assert.equal(processor.isEnabled(), false); assert.equal(processor.canProcess(file), false); - assert.deepEqual(await processor.prepare(file), { file, metadata: null }); + assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" }); } finally { globalThis.fetch = originalFetch; } @@ -37,9 +37,9 @@ test("admin-disabled policy and fetch failure both fall back to the original fil const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 }); try { globalThis.fetch = async () => ({ ok: true, json: async () => ({ browser_processing_beta_enabled: false, version: 1 }) }); - assert.deepEqual(await processor.prepare(file), { file, metadata: null }); + assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" }); globalThis.fetch = async () => { throw new Error("offline"); }; - assert.deepEqual(await processor.prepare(file), { file, metadata: null }); + assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" }); } finally { globalThis.fetch = originalFetch; } @@ -53,6 +53,7 @@ test("video routing is gated and audio never invokes FFmpeg", async () => { const processor = new BrowserSubmissionProcessor( { browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 }, async () => { calls += 1; return new File(["wav"], "clip.wav", { type: "audio/wav" }); }, + { prepareAudio: async () => new Float32Array(16000), classify: async () => [{ class: "Fireworks", score: .9 }] }, ); await processor.prepare(file); assert.equal(calls, 0); @@ -62,7 +63,7 @@ test("video routing is gated and audio never invokes FFmpeg", async () => { assert.equal(result.file.type, "audio/wav"); assert.equal(result.metadata.browser_processing_used, true); const disabled = new BrowserSubmissionProcessor({ browserProcessingBeta: false }, async () => { throw new Error("must not run"); }); - assert.deepEqual(await disabled.prepare(video), { file: video, metadata: null }); + assert.deepEqual(await disabled.prepare(video), { file: video, metadata: null, gate: "unavailable" }); } finally { globalThis.fetch = originalFetch; } diff --git a/frontend/tests/browser-yamnet-classifier.test.mjs b/frontend/tests/browser-yamnet-classifier.test.mjs new file mode 100644 index 0000000..fd340d8 --- /dev/null +++ b/frontend/tests/browser-yamnet-classifier.test.mjs @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { BrowserYamnetClassifier } from "../src/scripts/browser-yamnet-classifier.js"; + +test("YAMNet peak scores are mapped and all owned resources are disposed", async () => { + const originalFetch = globalThis.fetch; + const disposed = []; + const values = new Float32Array(2 * 521); + values[0] = .4; + values[521] = .9; + const output = { shape: [2, 521], data: async () => values, dispose: () => disposed.push("output") }; + const model = { executeAsync: async () => [output], dispose: () => disposed.push("model") }; + const tf = { + ready: async () => {}, getBackend: () => "cpu", memory: () => ({ numTensors: 0 }), + loadGraphModel: async () => model, + tensor1d: () => ({ dispose: () => disposed.push("input") }), + }; + globalThis.fetch = async () => ({ ok: true, json: async () => ["Fireworks", ...Array(520).fill("Other")] }); + try { + const predictions = await BrowserYamnetClassifier.classify(new Float32Array(16000), { + modelUrl: "/static/browser-yamnet/model.json", classMapUrl: "/static/browser-yamnet/yamnet_class_map.json", + loadTensorFlow: async () => tf, + }); + assert.equal(predictions[0].class, "Fireworks"); + assert.equal(predictions[0].score, values[521]); + assert.equal(predictions[0].timeSeconds, .48); + assert.deepEqual(disposed, ["input", "output", "model"]); + } finally { globalThis.fetch = originalFetch; } +}); + +test("model failure still disposes the loaded model", async () => { + const originalFetch = globalThis.fetch; + let disposed = false; + const tf = { + ready: async () => {}, getBackend: () => "cpu", memory: () => ({ numTensors: 0 }), + loadGraphModel: async () => ({ dispose: () => { disposed = true; } }), + }; + globalThis.fetch = async () => ({ ok: false }); + try { + await assert.rejects(BrowserYamnetClassifier.classify(new Float32Array(16000), { + modelUrl: "/model.json", classMapUrl: "/map.json", loadTensorFlow: async () => tf, + })); + assert.equal(disposed, true); + } finally { globalThis.fetch = originalFetch; } +}); diff --git a/locale/nl/LC_MESSAGES/django.mo b/locale/nl/LC_MESSAGES/django.mo index bd7ab42..355f5e0 100644 Binary files a/locale/nl/LC_MESSAGES/django.mo and b/locale/nl/LC_MESSAGES/django.mo differ diff --git a/locale/nl/LC_MESSAGES/django.po b/locale/nl/LC_MESSAGES/django.po index 3ab0b3b..b649d44 100644 --- a/locale/nl/LC_MESSAGES/django.po +++ b/locale/nl/LC_MESSAGES/django.po @@ -1215,3 +1215,51 @@ msgstr "Classificatie opgeslagen. Deze melding blijft openstaan." msgid "Preparing recording…" msgstr "Opname voorbereiden…" + +msgid "Checking recording…" +msgstr "Opname controleren…" + +msgid "Ready to submit." +msgstr "Klaar om te verzenden." + +msgid "Extracting audio from video…" +msgstr "Audio uit video halen…" + +msgid "Could not extract audio from this video. Please choose an audio recording." +msgstr "Audio uit deze video halen is niet gelukt. Kies een audio-opname." + +msgid "Preparation cancelled. Choose a recording to continue." +msgstr "Voorbereiding geannuleerd. Kies een opname om verder te gaan." + +msgid "Video processed on this device. Only extracted audio will be sent if you submit." +msgstr "De video is op dit apparaat verwerkt. Alleen de audio wordt verzonden als je de opname indient." + +msgid "This recording appears to contain speech, but no relevant sound was detected." +msgstr "Deze opname lijkt spraak te bevatten, maar er is geen relevant geluid gevonden." + +msgid "To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review." +msgstr "Om de privacy van mensen te beschermen, wordt deze opname niet automatisch geüpload. Je kunt de opname wel indienen voor handmatige beoordeling." + +msgid "No relevant sound was detected." +msgstr "Er is geen relevant geluid gevonden." + +msgid "BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review." +msgstr "BoomCast kon geen geluid herkennen waar deze dienst momenteel naar zoekt. Je kunt de opname wel indienen voor handmatige beoordeling." + +msgid "Recording checked. Choose another recording or submit for manual review." +msgstr "Opname gecontroleerd. Kies een andere opname of dien deze in voor handmatige beoordeling." + +msgid "Could not prepare this video for upload. Please choose an audio recording." +msgstr "Deze video kon niet veilig worden voorbereid voor upload. Kies een audio-opname." + +msgid "Choose another recording" +msgstr "Kies een andere opname" + +msgid "Submit for manual review anyway" +msgstr "Toch indienen voor handmatige beoordeling" + +msgid "Sent to Pending Review" +msgstr "Verzonden voor beoordeling" + +msgid "An administrator will review this recording." +msgstr "Een beheerder beoordeelt deze opname." diff --git a/package-lock.json b/package-lock.json index 8bfeddf..a391db0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,8 @@ "dependencies": { "@ffmpeg/core": "^0.12.10", "@ffmpeg/ffmpeg": "^0.12.15", - "@ffmpeg/util": "^0.12.2" + "@ffmpeg/util": "^0.12.2", + "@tensorflow/tfjs": "^4.22.0" }, "devDependencies": { "concurrently": "^9.1.2", @@ -863,6 +864,157 @@ "win32" ] }, + "node_modules/@tensorflow/tfjs": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs/-/tfjs-4.22.0.tgz", + "integrity": "sha512-0TrIrXs6/b7FLhLVNmfh8Sah6JgjBPH4mZ8JGb7NU6WW+cx00qK5BcAZxw7NCzxj6N8MRAIfHq+oNbPUNG5VAg==", + "license": "Apache-2.0", + "dependencies": { + "@tensorflow/tfjs-backend-cpu": "4.22.0", + "@tensorflow/tfjs-backend-webgl": "4.22.0", + "@tensorflow/tfjs-converter": "4.22.0", + "@tensorflow/tfjs-core": "4.22.0", + "@tensorflow/tfjs-data": "4.22.0", + "@tensorflow/tfjs-layers": "4.22.0", + "argparse": "^1.0.10", + "chalk": "^4.1.0", + "core-js": "3.29.1", + "regenerator-runtime": "^0.13.5", + "yargs": "^16.0.3" + }, + "bin": { + "tfjs-custom-module": "dist/tools/custom_module/cli.js" + } + }, + "node_modules/@tensorflow/tfjs-backend-cpu": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-backend-cpu/-/tfjs-backend-cpu-4.22.0.tgz", + "integrity": "sha512-1u0FmuLGuRAi8D2c3cocHTASGXOmHc/4OvoVDENJayjYkS119fcTcQf4iHrtLthWyDIPy3JiPhRrZQC9EwnhLw==", + "license": "Apache-2.0", + "dependencies": { + "@types/seedrandom": "^2.4.28", + "seedrandom": "^3.0.5" + }, + "engines": { + "yarn": ">= 1.3.2" + }, + "peerDependencies": { + "@tensorflow/tfjs-core": "4.22.0" + } + }, + "node_modules/@tensorflow/tfjs-backend-webgl": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-backend-webgl/-/tfjs-backend-webgl-4.22.0.tgz", + "integrity": "sha512-H535XtZWnWgNwSzv538czjVlbJebDl5QTMOth4RXr2p/kJ1qSIXE0vZvEtO+5EC9b00SvhplECny2yDewQb/Yg==", + "license": "Apache-2.0", + "dependencies": { + "@tensorflow/tfjs-backend-cpu": "4.22.0", + "@types/offscreencanvas": "~2019.3.0", + "@types/seedrandom": "^2.4.28", + "seedrandom": "^3.0.5" + }, + "engines": { + "yarn": ">= 1.3.2" + }, + "peerDependencies": { + "@tensorflow/tfjs-core": "4.22.0" + } + }, + "node_modules/@tensorflow/tfjs-converter": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-converter/-/tfjs-converter-4.22.0.tgz", + "integrity": "sha512-PT43MGlnzIo+YfbsjM79Lxk9lOq6uUwZuCc8rrp0hfpLjF6Jv8jS84u2jFb+WpUeuF4K33ZDNx8CjiYrGQ2trQ==", + "license": "Apache-2.0", + "peerDependencies": { + "@tensorflow/tfjs-core": "4.22.0" + } + }, + "node_modules/@tensorflow/tfjs-core": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-core/-/tfjs-core-4.22.0.tgz", + "integrity": "sha512-LEkOyzbknKFoWUwfkr59vSB68DMJ4cjwwHgicXN0DUi3a0Vh1Er3JQqCI1Hl86GGZQvY8ezVrtDIvqR1ZFW55A==", + "license": "Apache-2.0", + "dependencies": { + "@types/long": "^4.0.1", + "@types/offscreencanvas": "~2019.7.0", + "@types/seedrandom": "^2.4.28", + "@webgpu/types": "0.1.38", + "long": "4.0.0", + "node-fetch": "~2.6.1", + "seedrandom": "^3.0.5" + }, + "engines": { + "yarn": ">= 1.3.2" + } + }, + "node_modules/@tensorflow/tfjs-core/node_modules/@types/offscreencanvas": { + "version": "2019.7.3", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz", + "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==", + "license": "MIT" + }, + "node_modules/@tensorflow/tfjs-data": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-data/-/tfjs-data-4.22.0.tgz", + "integrity": "sha512-dYmF3LihQIGvtgJrt382hSRH4S0QuAp2w1hXJI2+kOaEqo5HnUPG0k5KA6va+S1yUhx7UBToUKCBHeLHFQRV4w==", + "license": "Apache-2.0", + "dependencies": { + "@types/node-fetch": "^2.1.2", + "node-fetch": "~2.6.1", + "string_decoder": "^1.3.0" + }, + "peerDependencies": { + "@tensorflow/tfjs-core": "4.22.0", + "seedrandom": "^3.0.5" + } + }, + "node_modules/@tensorflow/tfjs-layers": { + "version": "4.22.0", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-layers/-/tfjs-layers-4.22.0.tgz", + "integrity": "sha512-lybPj4ZNj9iIAPUj7a8ZW1hg8KQGfqWLlCZDi9eM/oNKCCAgchiyzx8OrYoWmRrB+AM6VNEeIT+2gZKg5ReihA==", + "license": "Apache-2.0 AND MIT", + "peerDependencies": { + "@tensorflow/tfjs-core": "4.22.0" + } + }, + "node_modules/@tensorflow/tfjs/node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/@tensorflow/tfjs/node_modules/yargs": { + "version": "16.2.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.2.tgz", + "integrity": "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w==", + "license": "MIT", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@tensorflow/tfjs/node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -870,11 +1022,53 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz", + "integrity": "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/@types/offscreencanvas": { + "version": "2019.3.0", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.3.0.tgz", + "integrity": "sha512-esIJx9bQg+QYF0ra8GnvfianIY8qWB0GBx54PK5Eps6m+xTj86KLavHv6qDhzKcu5UUOgNfJ2pWaIIV7TRUd9Q==", + "license": "MIT" + }, + "node_modules/@types/seedrandom": { + "version": "2.4.34", + "resolved": "https://registry.npmjs.org/@types/seedrandom/-/seedrandom-2.4.34.tgz", + "integrity": "sha512-ytDiArvrn/3Xk6/vtylys5tlY6eo7Ane0hvcx++TKo6RxQXuVfW0AF/oeWqAj9dN29SyhtawuXstgmPlwNcv/A==", + "license": "MIT" + }, + "node_modules/@webgpu/types": { + "version": "0.1.38", + "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.38.tgz", + "integrity": "sha512-7LrhVKz2PRh+DD7+S+PVaFd5HxaWQvoMqBbsV9fNJO1pjUs1P8bM2vQVNfk+3URTqbuTI7gkXi0rfsN0IadoBA==", + "license": "BSD-3-Clause" + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -884,7 +1078,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "license": "MIT", "dependencies": { "color-convert": "^2.0.1" @@ -896,11 +1089,38 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", @@ -917,7 +1137,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, "license": "MIT", "dependencies": { "has-flag": "^4.0.0" @@ -945,7 +1164,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -958,9 +1176,20 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, "license": "MIT" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/concurrently": { "version": "9.2.4", "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.4.tgz", @@ -986,13 +1215,91 @@ "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" } }, + "node_modules/core-js": { + "version": "3.29.1", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.29.1.tgz", + "integrity": "sha512-+jwgnhg6cQxKYIIjGtAHq2nwUOolo9eoFZ4sHfUH09BLXBgxnH4gA0zEd+t+BO2cNB8idaBtZFcFTRjQJRJmAw==", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, "license": "MIT" }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", @@ -1039,7 +1346,6 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -1063,6 +1369,22 @@ } } }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1078,36 +1400,166 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, + "node_modules/long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", + "license": "Apache-2.0" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/nanoid": { "version": "3.3.19", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", @@ -1127,6 +1579,26 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-StxNAxh15zr77QvvkmveSQ8uCQ4+v5FkvNTj0OESmiHu+VRi/gXArXtkWMElOsOUNLtUEvI4yS+rdtOHZTwlQA==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1176,11 +1648,16 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "license": "MIT" + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -1242,6 +1719,32 @@ "tslib": "^2.1.0" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/seedrandom": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==", + "license": "MIT" + }, "node_modules/shell-quote": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.9.0.tgz", @@ -1265,11 +1768,25 @@ "node": ">=0.10.0" } }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "license": "BSD-3-Clause" + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -1284,7 +1801,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -1326,6 +1842,12 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, "node_modules/tree-kill": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", @@ -1343,6 +1865,12 @@ "dev": true, "license": "0BSD" }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, "node_modules/vite": { "version": "6.4.3", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", @@ -1418,11 +1946,26 @@ } } }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", @@ -1440,7 +1983,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "license": "ISC", "engines": { "node": ">=10" diff --git a/package.json b/package.json index 39f8446..6081b9e 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "dependencies": { "@ffmpeg/core": "^0.12.10", "@ffmpeg/ffmpeg": "^0.12.15", - "@ffmpeg/util": "^0.12.2" + "@ffmpeg/util": "^0.12.2", + "@tensorflow/tfjs": "^4.22.0" } } diff --git a/scripts/BROWSER_YAMNET.md b/scripts/BROWSER_YAMNET.md new file mode 100644 index 0000000..919c9b4 --- /dev/null +++ b/scripts/BROWSER_YAMNET.md @@ -0,0 +1,18 @@ +# Browser YAMNet model + +The browser GraphModel uses the [official TensorFlow YAMNet implementation](https://github.com/tensorflow/models/tree/master/research/audioset/yamnet) and [published weights](https://storage.googleapis.com/audioset/yamnet.h5). The official 521-class AudioSet map is included beside it. Runtime assets live in `fireworks_detect/static/browser-yamnet/`; browsers fetch them only from BoomCast. `VERSION` records the pinned source revision and TensorFlow version. + +To regenerate, use a dedicated conversion environment. The conversion script downloads the pinned source and weights, exports a SavedModel, converts it to a TensorFlow.js GraphModel, and writes the class map and version file. It supplies scoped empty modules for the converter's unused TF Decision Forests, TF Hub, and JAX imports; YAMNet does not use those features. The following package set was used for this artifact on Python 3.13: + +```sh +mkdir -p .yamnet-build-tmp +python3 -m venv .yamnet-convert +TMPDIR="$PWD/.yamnet-build-tmp" .yamnet-convert/bin/pip install --no-cache-dir tensorflow-cpu tensorflowjs tensorflow-hub tf-keras +TMPDIR="$PWD/.yamnet-build-tmp" .yamnet-convert/bin/pip install --no-cache-dir --no-deps tensorflowjs==4.22.0 +TF_USE_LEGACY_KERAS=1 TMPDIR="$PWD/.yamnet-build-tmp" .yamnet-convert/bin/python scripts/build_browser_yamnet.py +node scripts/verify_browser_yamnet.mjs +npm run build +python manage.py collectstatic --noinput +``` + +The verifier runs an actual TensorFlow.js inference and checks the 521-class score output. Keep the class map aligned with the model weights. The browser's relevance and speech thresholds are triage settings in `browser_policy.py`; the server classifier remains authoritative. Compare changed model outputs with representative clips before enabling the beta after an upgrade. diff --git a/scripts/build_browser_yamnet.py b/scripts/build_browser_yamnet.py new file mode 100644 index 0000000..9e2c2fd --- /dev/null +++ b/scripts/build_browser_yamnet.py @@ -0,0 +1,80 @@ +"""Regenerate the self-hosted YAMNet TensorFlow.js GraphModel. + +Run in a dedicated Python environment with tensorflow-cpu, tensorflowjs, +TensorFlow Hub, and tf-keras installed. Uses the official TensorFlow YAMNet +implementation and published weights; normal site traffic never contacts them. +""" +import csv +import json +import os +import subprocess +import sys +import tempfile +import urllib.request +from pathlib import Path + +SOURCE_REVISION = "c651073789719ff39dcf51406733bbcaaafb43f2" +SOURCE_BASE = f"https://raw.githubusercontent.com/tensorflow/models/{SOURCE_REVISION}/research/audioset/yamnet" +WEIGHTS_URL = "https://storage.googleapis.com/audioset/yamnet.h5" +OUTPUT = Path(__file__).resolve().parents[1] / "fireworks_detect/static/browser-yamnet" + + +def download(url, target): + urllib.request.urlretrieve(url, target) + + +def main(): + os.environ.setdefault("TF_USE_LEGACY_KERAS", "1") + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + for name in ("yamnet.py", "features.py", "params.py", "yamnet_class_map.csv"): + download(f"{SOURCE_BASE}/{name}", directory / name) + download(WEIGHTS_URL, directory / "yamnet.h5") + sys.path.insert(0, str(directory)) + import tensorflow as tf + import params + import yamnet + + class Export(tf.Module): + def __init__(self): + super().__init__() + self.model = yamnet.yamnet_frames_model(params.Params(tflite_compatible=True)) + self.model.load_weights(str(directory / "yamnet.h5")) + + @tf.function(input_signature=[tf.TensorSpec([None], tf.float32, name="waveform")]) + def classify(self, waveform): + scores, embeddings, spectrogram = self.model(waveform) + return {"predictions": scores, "embeddings": embeddings, "log_mel_spectrogram": spectrogram} + + export = Export() + with tempfile.TemporaryDirectory() as saved_dir: + tf.saved_model.save(export, saved_dir, signatures={"serving_default": export.classify}) + OUTPUT.mkdir(parents=True, exist_ok=True) + # The converter imports TF Decision Forests unconditionally even + # though YAMNet contains no decision forest ops. Keep this stub + # scoped to the conversion subprocess rather than installing TFDF. + (directory / "tensorflow_decision_forests.py").write_text("") + (directory / "tensorflow_hub.py").write_text("") + (directory / "jax/experimental").mkdir(parents=True) + (directory / "jax/__init__.py").write_text("") + (directory / "jax/experimental/__init__.py").write_text("") + (directory / "jax/experimental/jax2tf.py").write_text("") + converter_env = {**os.environ, "PYTHONPATH": str(directory)} + subprocess.run([ + sys.executable, "-m", "tensorflowjs.converters.converter", + "--input_format=tf_saved_model", "--output_format=tfjs_graph_model", + "--signature_name=serving_default", saved_dir, str(OUTPUT), + ], check=True, env=converter_env) + with (directory / "yamnet_class_map.csv").open(newline="") as source: + rows = list(csv.DictReader(source)) + assert len(rows) == 521 + (OUTPUT / "yamnet_class_map.csv").write_bytes((directory / "yamnet_class_map.csv").read_bytes()) + (OUTPUT / "yamnet_class_map.json").write_text(json.dumps([row["display_name"] for row in rows])) + (OUTPUT / "VERSION").write_text( + f"google-yamnet-1\nsource_revision={SOURCE_REVISION}\ntensorflow={tf.__version__}\n" + ) + print(f"Browser YAMNet GraphModel written to {OUTPUT}") + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_browser_yamnet.mjs b/scripts/verify_browser_yamnet.mjs new file mode 100644 index 0000000..b045cb3 --- /dev/null +++ b/scripts/verify_browser_yamnet.mjs @@ -0,0 +1,29 @@ +import { readFileSync } from "node:fs"; +import { join, dirname } from "node:path"; +import * as tf from "@tensorflow/tfjs"; + +const directory = new URL("../fireworks_detect/static/browser-yamnet/", import.meta.url).pathname; +const manifest = JSON.parse(readFileSync(join(directory, "model.json"), "utf8")); +const mapping = JSON.parse(readFileSync(join(directory, "yamnet_class_map.json"), "utf8")); +if (manifest.format !== "graph-model" || mapping.length !== 521) throw new Error("Invalid browser YAMNet assets"); +const specs = manifest.weightsManifest.flatMap((group) => group.weights); +const chunks = manifest.weightsManifest.flatMap((group) => group.paths.map((path) => readFileSync(join(directory, path)))); +const combined = Buffer.concat(chunks); +const model = await tf.loadGraphModel({ load: async () => ({ + modelTopology: manifest.modelTopology, + weightSpecs: specs, + weightData: combined.buffer.slice(combined.byteOffset, combined.byteOffset + combined.byteLength), +}) }); +const input = tf.zeros([16000]); +let outputs; +try { + outputs = await model.executeAsync(input); + const tensors = Array.isArray(outputs) ? outputs : [outputs]; + const scores = tensors.find((tensor) => tensor.shape.length === 2 && tensor.shape[1] === 521); + if (!scores || scores.shape[0] < 1) throw new Error("YAMNet did not produce scores"); + console.log("Verified browser YAMNet score tensor:", scores.shape); +} finally { + input.dispose(); + (Array.isArray(outputs) ? outputs : [outputs]).forEach((tensor) => tensor?.dispose()); + model.dispose(); +} diff --git a/staticfiles/browser-yamnet/VERSION b/staticfiles/browser-yamnet/VERSION new file mode 100644 index 0000000..79c436f --- /dev/null +++ b/staticfiles/browser-yamnet/VERSION @@ -0,0 +1,3 @@ +google-yamnet-1 +source_revision=c651073789719ff39dcf51406733bbcaaafb43f2 +tensorflow=2.21.0 diff --git a/staticfiles/browser-yamnet/group1-shard1of4.bin b/staticfiles/browser-yamnet/group1-shard1of4.bin new file mode 100644 index 0000000..0366fb3 Binary files /dev/null and b/staticfiles/browser-yamnet/group1-shard1of4.bin differ diff --git a/staticfiles/browser-yamnet/group1-shard2of4.bin b/staticfiles/browser-yamnet/group1-shard2of4.bin new file mode 100644 index 0000000..9ac72a5 Binary files /dev/null and b/staticfiles/browser-yamnet/group1-shard2of4.bin differ diff --git a/staticfiles/browser-yamnet/group1-shard3of4.bin b/staticfiles/browser-yamnet/group1-shard3of4.bin new file mode 100644 index 0000000..f9eb843 Binary files /dev/null and b/staticfiles/browser-yamnet/group1-shard3of4.bin differ diff --git a/staticfiles/browser-yamnet/group1-shard4of4.bin b/staticfiles/browser-yamnet/group1-shard4of4.bin new file mode 100644 index 0000000..ccc34d5 Binary files /dev/null and b/staticfiles/browser-yamnet/group1-shard4of4.bin differ diff --git a/staticfiles/browser-yamnet/model.json b/staticfiles/browser-yamnet/model.json new file mode 100644 index 0000000..7064fe3 --- /dev/null +++ b/staticfiles/browser-yamnet/model.json @@ -0,0 +1 @@ +{"format": "graph-model", "generatedBy": "2.21.0", "convertedBy": "TensorFlow.js Converter v4.22.0", "signature": {"inputs": {"waveform": {"name": "waveform:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}]}}}, "outputs": {"predictions": {"name": "Identity_2:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}, {"size": "521"}]}}, "log_mel_spectrogram": {"name": "Identity_1:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}, {"size": "64"}]}}, "embeddings": {"name": "Identity:0", "dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "-1"}, {"size": "1024"}]}}}}, "modelTopology": {"node": [{"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/zeros_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/ones_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/start", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/delta", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_3", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}, {"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/strided_slice", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Const", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add/x", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape/shape_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_step", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_7", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}, {"size": "257"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/0_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "unknown_5", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_4", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/zeros_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/ones_like", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/start", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/delta", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_3", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}, {"size": "5"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/strided_slice", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Const", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add/x", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape/shape_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_step", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0/0", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv_recip", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "unknown", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "3"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split/split_dim", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_3", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "400"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv/y", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "unknown_6", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}, {"size": "257"}]}}}}}, {"name": "unknown_8", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "257"}, {"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/y", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "3"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split/split_dim", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2/axis", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/1", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/2", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/3", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean/reduction_indices", "op": "Const", "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {"dim": [{"size": "2"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/MatMul/ReadVariableOp", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}, {"size": "521"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd/ReadVariableOp", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "521"}]}}}}}, {"name": "waveform", "op": "Placeholder", "attr": {"shape": {"shape": {"dim": [{"size": "-1"}]}}, "dtype": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "1"}, {"size": "32"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "32"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "32"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "32"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "32"}, {"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "64"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "64"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "64"}, {"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "128"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "128"}, {"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "128"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "128"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "128"}, {"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "256"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "256"}, {"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "256"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "256"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "256"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "1024"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "1024"}, {"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1024"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "3"}, {"size": "3"}, {"size": "512"}, {"size": "1"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_bn_offset", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_weights", "op": "Const", "attr": {"dtype": {"type": "DT_FLOAT"}, "value": {"tensor": {"dtype": "DT_FLOAT", "tensorShape": {"dim": [{"size": "1"}, {"size": "1"}, {"size": "512"}, {"size": "512"}]}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape/Shape", "op": "Shape", "input": ["waveform"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape/Shape", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_1", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_2"], "attr": {"begin_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "end_mask": {"i": "0"}, "shrink_axis_mask": {"i": "1"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract/Sub", "op": "Sub", "input": ["unknown", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.maximum_1/Maximum", "op": "Maximum", "input": ["StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice", "unknown"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.maximum/Maximum", "op": "Maximum", "input": ["unknown_2", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract/Sub"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_1/Sub", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.maximum_1/Maximum", "unknown"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.cast/Cast", "op": "Cast", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.subtract_1/Sub"], "attr": {"SrcT": {"type": "DT_INT32"}, "Truncate": {"b": false}, "DstT": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.cast/Cast", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv_recip"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.ceil/Ceil", "op": "Ceil", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.cast_1/Cast", "op": "Cast", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.ceil/Ceil"], "attr": {"SrcT": {"type": "DT_FLOAT"}, "Truncate": {"b": false}, "DstT": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply/Mul", "op": "Mul", "input": ["unknown_1", "StatefulPartitionedCall/yamnet_frames/tf.cast_1/Cast"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_2/Sub", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply/Mul", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_1/Sub"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add/AddV2", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.maximum/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_2/Sub"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0/0", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add/AddV2"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings_const_axis", "op": "Const", "input": ["^StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0"], "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings", "op": "ExpandDims", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings_const_axis"], "attr": {"Tdim": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad", "op": "Pad", "input": ["waveform", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings"], "attr": {"Tpaddings": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "op": "SplitV", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Shape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split/split_dim"], "attr": {"Tlen": {"type": "DT_INT32"}, "num_split": {"i": "3"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape/shape_1"], "attr": {"Tshape": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/sub_2", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/sub_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_step"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1_const_axis", "op": "Const", "input": ["^StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul"], "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add/x", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1", "op": "ExpandDims", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1_const_axis"], "attr": {"Tdim": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "op": "Maximum", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Const", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1", "op": "Range", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/start", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/delta"], "attr": {"Tidx": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length"], "attr": {"T": {"type": "DT_INT32"}, "axis": {"i": "0"}, "N": {"i": "2"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/StridedSlice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/zeros_like", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/ones_like"], "attr": {"begin_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "end_mask": {"i": "0"}, "shrink_axis_mask": {"i": "0"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul_1", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_2"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2/axis"], "attr": {"N": {"i": "3"}, "Tidx": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_1", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/StridedSlice", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape"], "attr": {"T": {"type": "DT_INT32"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add_1", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_3"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/GatherV2", "op": "GatherV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/strided_slice"], "attr": {"Tparams": {"type": "DT_FLOAT"}, "Taxis": {"type": "DT_INT32"}, "batch_dims": {"i": "0"}, "Tindices": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_4", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/GatherV2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2"], "attr": {"Tshape": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_1/Mul", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_4", "unknown_3"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape_1/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply_1/Mul"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.shape_1/Shape", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_1", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_2"], "attr": {"end_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "begin_mask": {"i": "0"}, "shrink_axis_mask": {"i": "1"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_4/Sub", "op": "Sub", "input": ["unknown_5", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_3/Sub", "op": "Sub", "input": ["unknown_4", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.subtract_3/Sub", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_5/Sub", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.subtract_4/Sub", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv", "StatefulPartitionedCall/yamnet_frames/tf.math.subtract_5/Sub"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/0_1", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad", "op": "Pad", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply_1/Mul", "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings"], "attr": {"Tpaddings": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul/MatMul", "op": "MatMul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad", "unknown_7"], "device": "/device:CPU:0", "attr": {"T": {"type": "DT_FLOAT"}, "transpose_b": {"b": false}, "grad_a": {"b": false}, "transpose_a": {"b": false}, "grad_b": {"b": false}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul_1/MatMul", "op": "MatMul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad", "unknown_6"], "device": "/device:CPU:0", "attr": {"T": {"type": "DT_FLOAT"}, "transpose_b": {"b": false}, "grad_b": {"b": false}, "transpose_a": {"b": false}, "grad_a": {"b": false}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_2/ArithmeticOptimizer/ReplaceMulWithSquare_Mul", "op": "Square", "input": ["StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul/MatMul"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_3/ArithmeticOptimizer/ReplaceMulWithSquare_Mul", "op": "Square", "input": ["StatefulPartitionedCall/yamnet_frames/tf.linalg.matmul_1/MatMul"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.add/Add", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.multiply_2/ArithmeticOptimizer/ReplaceMulWithSquare_Mul", "StatefulPartitionedCall/yamnet_frames/tf.math.multiply_3/ArithmeticOptimizer/ReplaceMulWithSquare_Mul"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.sqrt/Sqrt", "op": "Sqrt", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.add/Add"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/AddV2", "op": "_FusedMatMul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.sqrt/Sqrt", "unknown_8", "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/y"], "device": "/device:CPU:0", "attr": {"transpose_b": {"b": false}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA=="]}}, "num_args": {"i": "1"}, "transpose_a": {"b": false}, "epsilon": {"f": 0.0}, "leakyrelu_alpha": {"f": 0.2}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.math.log/Log", "op": "Log", "input": ["StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/AddV2"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "Identity_1", "op": "Identity", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.log/Log"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.log/Log"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "op": "SplitV", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Shape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split/split_dim"], "attr": {"Tlen": {"type": "DT_INT32"}, "num_split": {"i": "3"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape/shape_1"], "attr": {"T": {"type": "DT_INT32"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/sub_2", "op": "Sub", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul", "op": "Mul", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul/y"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv", "op": "FloorDiv", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/sub_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_step"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1_const_axis", "op": "Const", "input": ["^StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul"], "attr": {"dtype": {"type": "DT_INT32"}, "value": {"tensor": {"dtype": "DT_INT32", "tensorShape": {}}}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/axis"], "attr": {"N": {"i": "3"}, "Tidx": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add/x", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1", "op": "ExpandDims", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul", "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1_const_axis"], "attr": {"Tdim": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "op": "Maximum", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Const", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1", "op": "Range", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/start", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/delta"], "attr": {"Tidx": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape/1"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed_1", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Maximum", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length"], "attr": {"N": {"i": "2"}, "axis": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/StridedSlice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/tf.math.log/Log", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/zeros_like", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/ones_like"], "attr": {"begin_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "end_mask": {"i": "0"}, "new_axis_mask": {"i": "0"}, "shrink_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape"], "attr": {"Tshape": {"type": "DT_INT32"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2", "op": "ConcatV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split:2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2/axis"], "attr": {"T": {"type": "DT_INT32"}, "Tidx": {"type": "DT_INT32"}, "N": {"i": "3"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_1", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/StridedSlice", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add_1", "op": "AddV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_3"], "attr": {"T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/GatherV2", "op": "GatherV2", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add_1", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/strided_slice"], "attr": {"Tparams": {"type": "DT_FLOAT"}, "Taxis": {"type": "DT_INT32"}, "batch_dims": {"i": "0"}, "Tindices": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_4", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/GatherV2", "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Shape", "op": "Shape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_4"], "attr": {"out_type": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}, "experimentalType": {"typeId": "TFT_PRODUCT", "args": [{"typeId": "TFT_SHAPE_TENSOR", "args": [{"typeId": "TFT_INT32"}]}]}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice", "op": "StridedSlice", "input": ["StatefulPartitionedCall/yamnet_frames/reshape/Shape", "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack", "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_1", "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_2"], "attr": {"end_mask": {"i": "0"}, "Index": {"type": "DT_INT32"}, "begin_mask": {"i": "0"}, "shrink_axis_mask": {"i": "1"}, "new_axis_mask": {"i": "0"}, "ellipsis_mask": {"i": "0"}, "T": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape", "op": "Pack", "input": ["StatefulPartitionedCall/yamnet_frames/reshape/strided_slice", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/1", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/2", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/3"], "attr": {"T": {"type": "DT_INT32"}, "axis": {"i": "0"}, "N": {"i": "4"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape", "op": "Reshape", "input": ["StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_4", "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape"], "attr": {"T": {"type": "DT_FLOAT"}, "Tshape": {"type": "DT_INT32"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/reshape/Reshape", "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "data_format": {"s": "TkhXQw=="}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer1/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "num_host_args": {"i": "0"}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"num_host_args": {"i": "0"}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "data_format": {"s": "TkhXQw=="}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "num_args": {"i": "1"}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"TArgs": {"list": {"type": ["DT_FLOAT"]}}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "data_format": {"s": "TkhXQw=="}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "num_host_args": {"i": "0"}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "2", "2", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "num_host_args": {"i": "0"}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "filter_format": {"s": "SFdJTw=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise", "op": "FusedDepthwiseConv2dNative", "input": ["StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_weights", "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_bn_offset"], "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "padding": {"s": "U0FNRQ=="}, "explicit_paddings": {"list": {}}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/relu/Relu", "op": "_FusedConv2D", "input": ["StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise", "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_weights", "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_bn_offset"], "device": "/device:CPU:0", "attr": {"data_format": {"s": "TkhXQw=="}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA==", "UmVsdQ=="]}}, "num_host_args": {"i": "0"}, "strides": {"list": {"i": ["1", "1", "1", "1"]}}, "TArgs": {"list": {"type": ["DT_FLOAT"]}}, "filter_format": {"s": "SFdJTw=="}, "explicit_paddings": {"list": {}}, "use_cudnn_on_gpu": {"b": true}, "leakyrelu_alpha": {"f": 0.2}, "padding": {"s": "U0FNRQ=="}, "dilations": {"list": {"i": ["1", "1", "1", "1"]}}, "num_args": {"i": "1"}, "epsilon": {"f": 0.0}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean", "op": "Mean", "input": ["StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/relu/Relu", "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean/reduction_indices"], "attr": {"keep_dims": {"b": false}, "Tidx": {"type": "DT_INT32"}, "T": {"type": "DT_FLOAT"}}}, {"name": "Identity", "op": "Identity", "input": ["StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd", "op": "_FusedMatMul", "input": ["StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean", "StatefulPartitionedCall/yamnet_frames/dense/MatMul/ReadVariableOp", "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd/ReadVariableOp"], "device": "/device:CPU:0", "attr": {"leakyrelu_alpha": {"f": 0.2}, "fused_ops": {"list": {"s": ["Qmlhc0FkZA=="]}}, "num_args": {"i": "1"}, "transpose_a": {"b": false}, "epsilon": {"f": 0.0}, "transpose_b": {"b": false}, "T": {"type": "DT_FLOAT"}}}, {"name": "StatefulPartitionedCall/yamnet_frames/activation/Sigmoid", "op": "Sigmoid", "input": ["StatefulPartitionedCall/yamnet_frames/dense/BiasAdd"], "attr": {"T": {"type": "DT_FLOAT"}}}, {"name": "Identity_2", "op": "Identity", "input": ["StatefulPartitionedCall/yamnet_frames/activation/Sigmoid"], "attr": {"T": {"type": "DT_FLOAT"}}}], "library": {}, "versions": {"producer": 2474}}, "weightsManifest": [{"paths": ["group1-shard1of4.bin", "group1-shard2of4.bin", "group1-shard3of4.bin", "group1-shard4of4.bin"], "weights": [{"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/zeros_like", "shape": [2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/mul/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/ones_like", "shape": [2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/floordiv_3/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/values_1/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_1/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/start", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/range_1/delta", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_2/shape/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape_3", "shape": [1, 2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/strided_slice", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Const", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/add/x", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/Reshape/shape_1", "shape": [0], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_step", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/frame_length", "shape": [], "dtype": "int32"}, {"name": "unknown_7", "shape": [512, 257], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad_1/Pad/paddings/0_1", "shape": [2], "dtype": "int32"}, {"name": "unknown_5", "shape": [], "dtype": "int32"}, {"name": "unknown_4", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/zeros_like", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/mul/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/ones_like", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_3/y", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/values_1/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_1/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/start", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/range_1/delta", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/floordiv_2", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_2/shape/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape_3", "shape": [1, 5], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/strided_slice", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Const", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/add/x", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/Reshape/shape_1", "shape": [0], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_step", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/frame_length", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings/0/0", "shape": [], "dtype": "int32"}, {"name": "unknown_2", "shape": [], "dtype": "int32"}, {"name": "unknown_1", "shape": [], "dtype": "int32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.math.truediv/truediv_recip", "shape": [], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_1", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem/strided_slice/stack_2", "shape": [1], "dtype": "int32"}, {"name": "unknown", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/packed", "shape": [3], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/split/split_dim", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat_2/axis", "shape": [], "dtype": "int32"}, {"name": "unknown_3", "shape": [1, 400], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_1", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.getitem_1/strided_slice/stack_2", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.compat.v1.floor_div/FloorDiv/y", "shape": [], "dtype": "int32"}, {"name": "unknown_6", "shape": [512, 257], "dtype": "float32"}, {"name": "unknown_8", "shape": [257, 64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.__operators__.add_1/y", "shape": [], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/packed", "shape": [3], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/split/split_dim", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat_2/axis", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_1", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/strided_slice/stack_2", "shape": [1], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/1", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/2", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/reshape/Reshape/shape/3", "shape": [], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/global_average_pooling2d/Mean/reduction_indices", "shape": [2], "dtype": "int32"}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/MatMul/ReadVariableOp", "shape": [1024, 521], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/dense/BiasAdd/ReadVariableOp", "shape": [521], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_weights", "shape": [3, 3, 1, 32], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer1/conv/Conv2D_bn_offset", "shape": [32], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_weights", "shape": [3, 3, 32, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/depthwise_conv/depthwise_bn_offset", "shape": [32], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_weights", "shape": [1, 1, 32, 64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer2/pointwise_conv/Conv2D_bn_offset", "shape": [64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_weights", "shape": [3, 3, 64, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/depthwise_conv/depthwise_bn_offset", "shape": [64], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_weights", "shape": [1, 1, 64, 128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer3/pointwise_conv/Conv2D_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_weights", "shape": [3, 3, 128, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/depthwise_conv/depthwise_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_weights", "shape": [1, 1, 128, 128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer4/pointwise_conv/Conv2D_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_weights", "shape": [3, 3, 128, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/depthwise_conv/depthwise_bn_offset", "shape": [128], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_weights", "shape": [1, 1, 128, 256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer5/pointwise_conv/Conv2D_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_weights", "shape": [3, 3, 256, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/depthwise_conv/depthwise_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_weights", "shape": [1, 1, 256, 256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer13/pointwise_conv/Conv2D_bn_offset", "shape": [1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer6/pointwise_conv/Conv2D_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_weights", "shape": [3, 3, 256, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/depthwise_conv/depthwise_bn_offset", "shape": [256], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_weights", "shape": [1, 1, 256, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer7/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_weights", "shape": [3, 3, 1024, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer8/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/depthwise_conv/depthwise_bn_offset", "shape": [1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer9/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_weights", "shape": [1, 1, 1024, 1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer10/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer14/pointwise_conv/Conv2D_bn_offset", "shape": [1024], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer11/pointwise_conv/Conv2D_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_weights", "shape": [3, 3, 512, 1], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/depthwise_conv/depthwise_bn_offset", "shape": [512], "dtype": "float32"}, {"name": "StatefulPartitionedCall/yamnet_frames/layer12/pointwise_conv/Conv2D_weights", "shape": [1, 1, 512, 512], "dtype": "float32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.compat.v1.pad/Pad/paddings_const_axis", "shape": [], "dtype": "int32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame/frame/concat/values_1_const_axis", "shape": [], "dtype": "int32"}, {"name": "ConstantFolding/StatefulPartitionedCall/yamnet_frames/tf.signal.frame_1/frame/concat/values_1_const_axis", "shape": [], "dtype": "int32"}]}]} \ No newline at end of file diff --git a/staticfiles/browser-yamnet/yamnet_class_map.csv b/staticfiles/browser-yamnet/yamnet_class_map.csv new file mode 100644 index 0000000..9c07d81 --- /dev/null +++ b/staticfiles/browser-yamnet/yamnet_class_map.csv @@ -0,0 +1,522 @@ +index,mid,display_name +0,/m/09x0r,Speech +1,/m/0ytgt,"Child speech, kid speaking" +2,/m/01h8n0,Conversation +3,/m/02qldy,"Narration, monologue" +4,/m/0261r1,Babbling +5,/m/0brhx,Speech synthesizer +6,/m/07p6fty,Shout +7,/m/07q4ntr,Bellow +8,/m/07rwj3x,Whoop +9,/m/07sr1lc,Yell +10,/t/dd00135,Children shouting +11,/m/03qc9zr,Screaming +12,/m/02rtxlg,Whispering +13,/m/01j3sz,Laughter +14,/t/dd00001,Baby laughter +15,/m/07r660_,Giggle +16,/m/07s04w4,Snicker +17,/m/07sq110,Belly laugh +18,/m/07rgt08,"Chuckle, chortle" +19,/m/0463cq4,"Crying, sobbing" +20,/t/dd00002,"Baby cry, infant cry" +21,/m/07qz6j3,Whimper +22,/m/07qw_06,"Wail, moan" +23,/m/07plz5l,Sigh +24,/m/015lz1,Singing +25,/m/0l14jd,Choir +26,/m/01swy6,Yodeling +27,/m/02bk07,Chant +28,/m/01c194,Mantra +29,/t/dd00005,Child singing +30,/t/dd00006,Synthetic singing +31,/m/06bxc,Rapping +32,/m/02fxyj,Humming +33,/m/07s2xch,Groan +34,/m/07r4k75,Grunt +35,/m/01w250,Whistling +36,/m/0lyf6,Breathing +37,/m/07mzm6,Wheeze +38,/m/01d3sd,Snoring +39,/m/07s0dtb,Gasp +40,/m/07pyy8b,Pant +41,/m/07q0yl5,Snort +42,/m/01b_21,Cough +43,/m/0dl9sf8,Throat clearing +44,/m/01hsr_,Sneeze +45,/m/07ppn3j,Sniff +46,/m/06h7j,Run +47,/m/07qv_x_,Shuffle +48,/m/07pbtc8,"Walk, footsteps" +49,/m/03cczk,"Chewing, mastication" +50,/m/07pdhp0,Biting +51,/m/0939n_,Gargling +52,/m/01g90h,Stomach rumble +53,/m/03q5_w,"Burping, eructation" +54,/m/02p3nc,Hiccup +55,/m/02_nn,Fart +56,/m/0k65p,Hands +57,/m/025_jnm,Finger snapping +58,/m/0l15bq,Clapping +59,/m/01jg02,"Heart sounds, heartbeat" +60,/m/01jg1z,Heart murmur +61,/m/053hz1,Cheering +62,/m/028ght,Applause +63,/m/07rkbfh,Chatter +64,/m/03qtwd,Crowd +65,/m/07qfr4h,"Hubbub, speech noise, speech babble" +66,/t/dd00013,Children playing +67,/m/0jbk,Animal +68,/m/068hy,"Domestic animals, pets" +69,/m/0bt9lr,Dog +70,/m/05tny_,Bark +71,/m/07r_k2n,Yip +72,/m/07qf0zm,Howl +73,/m/07rc7d9,Bow-wow +74,/m/0ghcn6,Growling +75,/t/dd00136,Whimper (dog) +76,/m/01yrx,Cat +77,/m/02yds9,Purr +78,/m/07qrkrw,Meow +79,/m/07rjwbb,Hiss +80,/m/07r81j2,Caterwaul +81,/m/0ch8v,"Livestock, farm animals, working animals" +82,/m/03k3r,Horse +83,/m/07rv9rh,Clip-clop +84,/m/07q5rw0,"Neigh, whinny" +85,/m/01xq0k1,"Cattle, bovinae" +86,/m/07rpkh9,Moo +87,/m/0239kh,Cowbell +88,/m/068zj,Pig +89,/t/dd00018,Oink +90,/m/03fwl,Goat +91,/m/07q0h5t,Bleat +92,/m/07bgp,Sheep +93,/m/025rv6n,Fowl +94,/m/09b5t,"Chicken, rooster" +95,/m/07st89h,Cluck +96,/m/07qn5dc,"Crowing, cock-a-doodle-doo" +97,/m/01rd7k,Turkey +98,/m/07svc2k,Gobble +99,/m/09ddx,Duck +100,/m/07qdb04,Quack +101,/m/0dbvp,Goose +102,/m/07qwf61,Honk +103,/m/01280g,Wild animals +104,/m/0cdnk,"Roaring cats (lions, tigers)" +105,/m/04cvmfc,Roar +106,/m/015p6,Bird +107,/m/020bb7,"Bird vocalization, bird call, bird song" +108,/m/07pggtn,"Chirp, tweet" +109,/m/07sx8x_,Squawk +110,/m/0h0rv,"Pigeon, dove" +111,/m/07r_25d,Coo +112,/m/04s8yn,Crow +113,/m/07r5c2p,Caw +114,/m/09d5_,Owl +115,/m/07r_80w,Hoot +116,/m/05_wcq,"Bird flight, flapping wings" +117,/m/01z5f,"Canidae, dogs, wolves" +118,/m/06hps,"Rodents, rats, mice" +119,/m/04rmv,Mouse +120,/m/07r4gkf,Patter +121,/m/03vt0,Insect +122,/m/09xqv,Cricket +123,/m/09f96,Mosquito +124,/m/0h2mp,"Fly, housefly" +125,/m/07pjwq1,Buzz +126,/m/01h3n,"Bee, wasp, etc." +127,/m/09ld4,Frog +128,/m/07st88b,Croak +129,/m/078jl,Snake +130,/m/07qn4z3,Rattle +131,/m/032n05,Whale vocalization +132,/m/04rlf,Music +133,/m/04szw,Musical instrument +134,/m/0fx80y,Plucked string instrument +135,/m/0342h,Guitar +136,/m/02sgy,Electric guitar +137,/m/018vs,Bass guitar +138,/m/042v_gx,Acoustic guitar +139,/m/06w87,"Steel guitar, slide guitar" +140,/m/01glhc,Tapping (guitar technique) +141,/m/07s0s5r,Strum +142,/m/018j2,Banjo +143,/m/0jtg0,Sitar +144,/m/04rzd,Mandolin +145,/m/01bns_,Zither +146,/m/07xzm,Ukulele +147,/m/05148p4,Keyboard (musical) +148,/m/05r5c,Piano +149,/m/01s0ps,Electric piano +150,/m/013y1f,Organ +151,/m/03xq_f,Electronic organ +152,/m/03gvt,Hammond organ +153,/m/0l14qv,Synthesizer +154,/m/01v1d8,Sampler +155,/m/03q5t,Harpsichord +156,/m/0l14md,Percussion +157,/m/02hnl,Drum kit +158,/m/0cfdd,Drum machine +159,/m/026t6,Drum +160,/m/06rvn,Snare drum +161,/m/03t3fj,Rimshot +162,/m/02k_mr,Drum roll +163,/m/0bm02,Bass drum +164,/m/011k_j,Timpani +165,/m/01p970,Tabla +166,/m/01qbl,Cymbal +167,/m/03qtq,Hi-hat +168,/m/01sm1g,Wood block +169,/m/07brj,Tambourine +170,/m/05r5wn,Rattle (instrument) +171,/m/0xzly,Maraca +172,/m/0mbct,Gong +173,/m/016622,Tubular bells +174,/m/0j45pbj,Mallet percussion +175,/m/0dwsp,"Marimba, xylophone" +176,/m/0dwtp,Glockenspiel +177,/m/0dwt5,Vibraphone +178,/m/0l156b,Steelpan +179,/m/05pd6,Orchestra +180,/m/01kcd,Brass instrument +181,/m/0319l,French horn +182,/m/07gql,Trumpet +183,/m/07c6l,Trombone +184,/m/0l14_3,Bowed string instrument +185,/m/02qmj0d,String section +186,/m/07y_7,"Violin, fiddle" +187,/m/0d8_n,Pizzicato +188,/m/01xqw,Cello +189,/m/02fsn,Double bass +190,/m/085jw,"Wind instrument, woodwind instrument" +191,/m/0l14j_,Flute +192,/m/06ncr,Saxophone +193,/m/01wy6,Clarinet +194,/m/03m5k,Harp +195,/m/0395lw,Bell +196,/m/03w41f,Church bell +197,/m/027m70_,Jingle bell +198,/m/0gy1t2s,Bicycle bell +199,/m/07n_g,Tuning fork +200,/m/0f8s22,Chime +201,/m/026fgl,Wind chime +202,/m/0150b9,Change ringing (campanology) +203,/m/03qjg,Harmonica +204,/m/0mkg,Accordion +205,/m/0192l,Bagpipes +206,/m/02bxd,Didgeridoo +207,/m/0l14l2,Shofar +208,/m/07kc_,Theremin +209,/m/0l14t7,Singing bowl +210,/m/01hgjl,Scratching (performance technique) +211,/m/064t9,Pop music +212,/m/0glt670,Hip hop music +213,/m/02cz_7,Beatboxing +214,/m/06by7,Rock music +215,/m/03lty,Heavy metal +216,/m/05r6t,Punk rock +217,/m/0dls3,Grunge +218,/m/0dl5d,Progressive rock +219,/m/07sbbz2,Rock and roll +220,/m/05w3f,Psychedelic rock +221,/m/06j6l,Rhythm and blues +222,/m/0gywn,Soul music +223,/m/06cqb,Reggae +224,/m/01lyv,Country +225,/m/015y_n,Swing music +226,/m/0gg8l,Bluegrass +227,/m/02x8m,Funk +228,/m/02w4v,Folk music +229,/m/06j64v,Middle Eastern music +230,/m/03_d0,Jazz +231,/m/026z9,Disco +232,/m/0ggq0m,Classical music +233,/m/05lls,Opera +234,/m/02lkt,Electronic music +235,/m/03mb9,House music +236,/m/07gxw,Techno +237,/m/07s72n,Dubstep +238,/m/0283d,Drum and bass +239,/m/0m0jc,Electronica +240,/m/08cyft,Electronic dance music +241,/m/0fd3y,Ambient music +242,/m/07lnk,Trance music +243,/m/0g293,Music of Latin America +244,/m/0ln16,Salsa music +245,/m/0326g,Flamenco +246,/m/0155w,Blues +247,/m/05fw6t,Music for children +248,/m/02v2lh,New-age music +249,/m/0y4f8,Vocal music +250,/m/0z9c,A capella +251,/m/0164x2,Music of Africa +252,/m/0145m,Afrobeat +253,/m/02mscn,Christian music +254,/m/016cjb,Gospel music +255,/m/028sqc,Music of Asia +256,/m/015vgc,Carnatic music +257,/m/0dq0md,Music of Bollywood +258,/m/06rqw,Ska +259,/m/02p0sh1,Traditional music +260,/m/05rwpb,Independent music +261,/m/074ft,Song +262,/m/025td0t,Background music +263,/m/02cjck,Theme music +264,/m/03r5q_,Jingle (music) +265,/m/0l14gg,Soundtrack music +266,/m/07pkxdp,Lullaby +267,/m/01z7dr,Video game music +268,/m/0140xf,Christmas music +269,/m/0ggx5q,Dance music +270,/m/04wptg,Wedding music +271,/t/dd00031,Happy music +272,/t/dd00033,Sad music +273,/t/dd00034,Tender music +274,/t/dd00035,Exciting music +275,/t/dd00036,Angry music +276,/t/dd00037,Scary music +277,/m/03m9d0z,Wind +278,/m/09t49,Rustling leaves +279,/t/dd00092,Wind noise (microphone) +280,/m/0jb2l,Thunderstorm +281,/m/0ngt1,Thunder +282,/m/0838f,Water +283,/m/06mb1,Rain +284,/m/07r10fb,Raindrop +285,/t/dd00038,Rain on surface +286,/m/0j6m2,Stream +287,/m/0j2kx,Waterfall +288,/m/05kq4,Ocean +289,/m/034srq,"Waves, surf" +290,/m/06wzb,Steam +291,/m/07swgks,Gurgling +292,/m/02_41,Fire +293,/m/07pzfmf,Crackle +294,/m/07yv9,Vehicle +295,/m/019jd,"Boat, Water vehicle" +296,/m/0hsrw,"Sailboat, sailing ship" +297,/m/056ks2,"Rowboat, canoe, kayak" +298,/m/02rlv9,"Motorboat, speedboat" +299,/m/06q74,Ship +300,/m/012f08,Motor vehicle (road) +301,/m/0k4j,Car +302,/m/0912c9,"Vehicle horn, car horn, honking" +303,/m/07qv_d5,Toot +304,/m/02mfyn,Car alarm +305,/m/04gxbd,"Power windows, electric windows" +306,/m/07rknqz,Skidding +307,/m/0h9mv,Tire squeal +308,/t/dd00134,Car passing by +309,/m/0ltv,"Race car, auto racing" +310,/m/07r04,Truck +311,/m/0gvgw0,Air brake +312,/m/05x_td,"Air horn, truck horn" +313,/m/02rhddq,Reversing beeps +314,/m/03cl9h,"Ice cream truck, ice cream van" +315,/m/01bjv,Bus +316,/m/03j1ly,Emergency vehicle +317,/m/04qvtq,Police car (siren) +318,/m/012n7d,Ambulance (siren) +319,/m/012ndj,"Fire engine, fire truck (siren)" +320,/m/04_sv,Motorcycle +321,/m/0btp2,"Traffic noise, roadway noise" +322,/m/06d_3,Rail transport +323,/m/07jdr,Train +324,/m/04zmvq,Train whistle +325,/m/0284vy3,Train horn +326,/m/01g50p,"Railroad car, train wagon" +327,/t/dd00048,Train wheels squealing +328,/m/0195fx,"Subway, metro, underground" +329,/m/0k5j,Aircraft +330,/m/014yck,Aircraft engine +331,/m/04229,Jet engine +332,/m/02l6bg,"Propeller, airscrew" +333,/m/09ct_,Helicopter +334,/m/0cmf2,"Fixed-wing aircraft, airplane" +335,/m/0199g,Bicycle +336,/m/06_fw,Skateboard +337,/m/02mk9,Engine +338,/t/dd00065,Light engine (high frequency) +339,/m/08j51y,"Dental drill, dentist's drill" +340,/m/01yg9g,Lawn mower +341,/m/01j4z9,Chainsaw +342,/t/dd00066,Medium engine (mid frequency) +343,/t/dd00067,Heavy engine (low frequency) +344,/m/01h82_,Engine knocking +345,/t/dd00130,Engine starting +346,/m/07pb8fc,Idling +347,/m/07q2z82,"Accelerating, revving, vroom" +348,/m/02dgv,Door +349,/m/03wwcy,Doorbell +350,/m/07r67yg,Ding-dong +351,/m/02y_763,Sliding door +352,/m/07rjzl8,Slam +353,/m/07r4wb8,Knock +354,/m/07qcpgn,Tap +355,/m/07q6cd_,Squeak +356,/m/0642b4,Cupboard open or close +357,/m/0fqfqc,Drawer open or close +358,/m/04brg2,"Dishes, pots, and pans" +359,/m/023pjk,"Cutlery, silverware" +360,/m/07pn_8q,Chopping (food) +361,/m/0dxrf,Frying (food) +362,/m/0fx9l,Microwave oven +363,/m/02pjr4,Blender +364,/m/02jz0l,"Water tap, faucet" +365,/m/0130jx,Sink (filling or washing) +366,/m/03dnzn,Bathtub (filling or washing) +367,/m/03wvsk,Hair dryer +368,/m/01jt3m,Toilet flush +369,/m/012xff,Toothbrush +370,/m/04fgwm,Electric toothbrush +371,/m/0d31p,Vacuum cleaner +372,/m/01s0vc,Zipper (clothing) +373,/m/03v3yw,Keys jangling +374,/m/0242l,Coin (dropping) +375,/m/01lsmm,Scissors +376,/m/02g901,"Electric shaver, electric razor" +377,/m/05rj2,Shuffling cards +378,/m/0316dw,Typing +379,/m/0c2wf,Typewriter +380,/m/01m2v,Computer keyboard +381,/m/081rb,Writing +382,/m/07pp_mv,Alarm +383,/m/07cx4,Telephone +384,/m/07pp8cl,Telephone bell ringing +385,/m/01hnzm,Ringtone +386,/m/02c8p,"Telephone dialing, DTMF" +387,/m/015jpf,Dial tone +388,/m/01z47d,Busy signal +389,/m/046dlr,Alarm clock +390,/m/03kmc9,Siren +391,/m/0dgbq,Civil defense siren +392,/m/030rvx,Buzzer +393,/m/01y3hg,"Smoke detector, smoke alarm" +394,/m/0c3f7m,Fire alarm +395,/m/04fq5q,Foghorn +396,/m/0l156k,Whistle +397,/m/06hck5,Steam whistle +398,/t/dd00077,Mechanisms +399,/m/02bm9n,"Ratchet, pawl" +400,/m/01x3z,Clock +401,/m/07qjznt,Tick +402,/m/07qjznl,Tick-tock +403,/m/0l7xg,Gears +404,/m/05zc1,Pulleys +405,/m/0llzx,Sewing machine +406,/m/02x984l,Mechanical fan +407,/m/025wky1,Air conditioning +408,/m/024dl,Cash register +409,/m/01m4t,Printer +410,/m/0dv5r,Camera +411,/m/07bjf,Single-lens reflex camera +412,/m/07k1x,Tools +413,/m/03l9g,Hammer +414,/m/03p19w,Jackhammer +415,/m/01b82r,Sawing +416,/m/02p01q,Filing (rasp) +417,/m/023vsd,Sanding +418,/m/0_ksk,Power tool +419,/m/01d380,Drill +420,/m/014zdl,Explosion +421,/m/032s66,"Gunshot, gunfire" +422,/m/04zjc,Machine gun +423,/m/02z32qm,Fusillade +424,/m/0_1c,Artillery fire +425,/m/073cg4,Cap gun +426,/m/0g6b5,Fireworks +427,/g/122z_qxw,Firecracker +428,/m/07qsvvw,"Burst, pop" +429,/m/07pxg6y,Eruption +430,/m/07qqyl4,Boom +431,/m/083vt,Wood +432,/m/07pczhz,Chop +433,/m/07pl1bw,Splinter +434,/m/07qs1cx,Crack +435,/m/039jq,Glass +436,/m/07q7njn,"Chink, clink" +437,/m/07rn7sz,Shatter +438,/m/04k94,Liquid +439,/m/07rrlb6,"Splash, splatter" +440,/m/07p6mqd,Slosh +441,/m/07qlwh6,Squish +442,/m/07r5v4s,Drip +443,/m/07prgkl,Pour +444,/m/07pqc89,"Trickle, dribble" +445,/t/dd00088,Gush +446,/m/07p7b8y,Fill (with liquid) +447,/m/07qlf79,Spray +448,/m/07ptzwd,Pump (liquid) +449,/m/07ptfmf,Stir +450,/m/0dv3j,Boiling +451,/m/0790c,Sonar +452,/m/0dl83,Arrow +453,/m/07rqsjt,"Whoosh, swoosh, swish" +454,/m/07qnq_y,"Thump, thud" +455,/m/07rrh0c,Thunk +456,/m/0b_fwt,Electronic tuner +457,/m/02rr_,Effects unit +458,/m/07m2kt,Chorus effect +459,/m/018w8,Basketball bounce +460,/m/07pws3f,Bang +461,/m/07ryjzk,"Slap, smack" +462,/m/07rdhzs,"Whack, thwack" +463,/m/07pjjrj,"Smash, crash" +464,/m/07pc8lb,Breaking +465,/m/07pqn27,Bouncing +466,/m/07rbp7_,Whip +467,/m/07pyf11,Flap +468,/m/07qb_dv,Scratch +469,/m/07qv4k0,Scrape +470,/m/07pdjhy,Rub +471,/m/07s8j8t,Roll +472,/m/07plct2,Crushing +473,/t/dd00112,"Crumpling, crinkling" +474,/m/07qcx4z,Tearing +475,/m/02fs_r,"Beep, bleep" +476,/m/07qwdck,Ping +477,/m/07phxs1,Ding +478,/m/07rv4dm,Clang +479,/m/07s02z0,Squeal +480,/m/07qh7jl,Creak +481,/m/07qwyj0,Rustle +482,/m/07s34ls,Whir +483,/m/07qmpdm,Clatter +484,/m/07p9k1k,Sizzle +485,/m/07qc9xj,Clicking +486,/m/07rwm0c,Clickety-clack +487,/m/07phhsh,Rumble +488,/m/07qyrcz,Plop +489,/m/07qfgpx,"Jingle, tinkle" +490,/m/07rcgpl,Hum +491,/m/07p78v5,Zing +492,/t/dd00121,Boing +493,/m/07s12q4,Crunch +494,/m/028v0c,Silence +495,/m/01v_m0,Sine wave +496,/m/0b9m1,Harmonic +497,/m/0hdsk,Chirp tone +498,/m/0c1dj,Sound effect +499,/m/07pt_g0,Pulse +500,/t/dd00125,"Inside, small room" +501,/t/dd00126,"Inside, large room or hall" +502,/t/dd00127,"Inside, public space" +503,/t/dd00128,"Outside, urban or manmade" +504,/t/dd00129,"Outside, rural or natural" +505,/m/01b9nn,Reverberation +506,/m/01jnbd,Echo +507,/m/096m7z,Noise +508,/m/06_y0by,Environmental noise +509,/m/07rgkc5,Static +510,/m/06xkwv,Mains hum +511,/m/0g12c5,Distortion +512,/m/08p9q4,Sidetone +513,/m/07szfh9,Cacophony +514,/m/0chx_,White noise +515,/m/0cj0r,Pink noise +516,/m/07p_0gm,Throbbing +517,/m/01jwx6,Vibration +518,/m/07c52,Television +519,/m/06bz3,Radio +520,/m/07hvw1,Field recording diff --git a/staticfiles/browser-yamnet/yamnet_class_map.json b/staticfiles/browser-yamnet/yamnet_class_map.json new file mode 100644 index 0000000..ee5d3bc --- /dev/null +++ b/staticfiles/browser-yamnet/yamnet_class_map.json @@ -0,0 +1 @@ +["Speech", "Child speech, kid speaking", "Conversation", "Narration, monologue", "Babbling", "Speech synthesizer", "Shout", "Bellow", "Whoop", "Yell", "Children shouting", "Screaming", "Whispering", "Laughter", "Baby laughter", "Giggle", "Snicker", "Belly laugh", "Chuckle, chortle", "Crying, sobbing", "Baby cry, infant cry", "Whimper", "Wail, moan", "Sigh", "Singing", "Choir", "Yodeling", "Chant", "Mantra", "Child singing", "Synthetic singing", "Rapping", "Humming", "Groan", "Grunt", "Whistling", "Breathing", "Wheeze", "Snoring", "Gasp", "Pant", "Snort", "Cough", "Throat clearing", "Sneeze", "Sniff", "Run", "Shuffle", "Walk, footsteps", "Chewing, mastication", "Biting", "Gargling", "Stomach rumble", "Burping, eructation", "Hiccup", "Fart", "Hands", "Finger snapping", "Clapping", "Heart sounds, heartbeat", "Heart murmur", "Cheering", "Applause", "Chatter", "Crowd", "Hubbub, speech noise, speech babble", "Children playing", "Animal", "Domestic animals, pets", "Dog", "Bark", "Yip", "Howl", "Bow-wow", "Growling", "Whimper (dog)", "Cat", "Purr", "Meow", "Hiss", "Caterwaul", "Livestock, farm animals, working animals", "Horse", "Clip-clop", "Neigh, whinny", "Cattle, bovinae", "Moo", "Cowbell", "Pig", "Oink", "Goat", "Bleat", "Sheep", "Fowl", "Chicken, rooster", "Cluck", "Crowing, cock-a-doodle-doo", "Turkey", "Gobble", "Duck", "Quack", "Goose", "Honk", "Wild animals", "Roaring cats (lions, tigers)", "Roar", "Bird", "Bird vocalization, bird call, bird song", "Chirp, tweet", "Squawk", "Pigeon, dove", "Coo", "Crow", "Caw", "Owl", "Hoot", "Bird flight, flapping wings", "Canidae, dogs, wolves", "Rodents, rats, mice", "Mouse", "Patter", "Insect", "Cricket", "Mosquito", "Fly, housefly", "Buzz", "Bee, wasp, etc.", "Frog", "Croak", "Snake", "Rattle", "Whale vocalization", "Music", "Musical instrument", "Plucked string instrument", "Guitar", "Electric guitar", "Bass guitar", "Acoustic guitar", "Steel guitar, slide guitar", "Tapping (guitar technique)", "Strum", "Banjo", "Sitar", "Mandolin", "Zither", "Ukulele", "Keyboard (musical)", "Piano", "Electric piano", "Organ", "Electronic organ", "Hammond organ", "Synthesizer", "Sampler", "Harpsichord", "Percussion", "Drum kit", "Drum machine", "Drum", "Snare drum", "Rimshot", "Drum roll", "Bass drum", "Timpani", "Tabla", "Cymbal", "Hi-hat", "Wood block", "Tambourine", "Rattle (instrument)", "Maraca", "Gong", "Tubular bells", "Mallet percussion", "Marimba, xylophone", "Glockenspiel", "Vibraphone", "Steelpan", "Orchestra", "Brass instrument", "French horn", "Trumpet", "Trombone", "Bowed string instrument", "String section", "Violin, fiddle", "Pizzicato", "Cello", "Double bass", "Wind instrument, woodwind instrument", "Flute", "Saxophone", "Clarinet", "Harp", "Bell", "Church bell", "Jingle bell", "Bicycle bell", "Tuning fork", "Chime", "Wind chime", "Change ringing (campanology)", "Harmonica", "Accordion", "Bagpipes", "Didgeridoo", "Shofar", "Theremin", "Singing bowl", "Scratching (performance technique)", "Pop music", "Hip hop music", "Beatboxing", "Rock music", "Heavy metal", "Punk rock", "Grunge", "Progressive rock", "Rock and roll", "Psychedelic rock", "Rhythm and blues", "Soul music", "Reggae", "Country", "Swing music", "Bluegrass", "Funk", "Folk music", "Middle Eastern music", "Jazz", "Disco", "Classical music", "Opera", "Electronic music", "House music", "Techno", "Dubstep", "Drum and bass", "Electronica", "Electronic dance music", "Ambient music", "Trance music", "Music of Latin America", "Salsa music", "Flamenco", "Blues", "Music for children", "New-age music", "Vocal music", "A capella", "Music of Africa", "Afrobeat", "Christian music", "Gospel music", "Music of Asia", "Carnatic music", "Music of Bollywood", "Ska", "Traditional music", "Independent music", "Song", "Background music", "Theme music", "Jingle (music)", "Soundtrack music", "Lullaby", "Video game music", "Christmas music", "Dance music", "Wedding music", "Happy music", "Sad music", "Tender music", "Exciting music", "Angry music", "Scary music", "Wind", "Rustling leaves", "Wind noise (microphone)", "Thunderstorm", "Thunder", "Water", "Rain", "Raindrop", "Rain on surface", "Stream", "Waterfall", "Ocean", "Waves, surf", "Steam", "Gurgling", "Fire", "Crackle", "Vehicle", "Boat, Water vehicle", "Sailboat, sailing ship", "Rowboat, canoe, kayak", "Motorboat, speedboat", "Ship", "Motor vehicle (road)", "Car", "Vehicle horn, car horn, honking", "Toot", "Car alarm", "Power windows, electric windows", "Skidding", "Tire squeal", "Car passing by", "Race car, auto racing", "Truck", "Air brake", "Air horn, truck horn", "Reversing beeps", "Ice cream truck, ice cream van", "Bus", "Emergency vehicle", "Police car (siren)", "Ambulance (siren)", "Fire engine, fire truck (siren)", "Motorcycle", "Traffic noise, roadway noise", "Rail transport", "Train", "Train whistle", "Train horn", "Railroad car, train wagon", "Train wheels squealing", "Subway, metro, underground", "Aircraft", "Aircraft engine", "Jet engine", "Propeller, airscrew", "Helicopter", "Fixed-wing aircraft, airplane", "Bicycle", "Skateboard", "Engine", "Light engine (high frequency)", "Dental drill, dentist's drill", "Lawn mower", "Chainsaw", "Medium engine (mid frequency)", "Heavy engine (low frequency)", "Engine knocking", "Engine starting", "Idling", "Accelerating, revving, vroom", "Door", "Doorbell", "Ding-dong", "Sliding door", "Slam", "Knock", "Tap", "Squeak", "Cupboard open or close", "Drawer open or close", "Dishes, pots, and pans", "Cutlery, silverware", "Chopping (food)", "Frying (food)", "Microwave oven", "Blender", "Water tap, faucet", "Sink (filling or washing)", "Bathtub (filling or washing)", "Hair dryer", "Toilet flush", "Toothbrush", "Electric toothbrush", "Vacuum cleaner", "Zipper (clothing)", "Keys jangling", "Coin (dropping)", "Scissors", "Electric shaver, electric razor", "Shuffling cards", "Typing", "Typewriter", "Computer keyboard", "Writing", "Alarm", "Telephone", "Telephone bell ringing", "Ringtone", "Telephone dialing, DTMF", "Dial tone", "Busy signal", "Alarm clock", "Siren", "Civil defense siren", "Buzzer", "Smoke detector, smoke alarm", "Fire alarm", "Foghorn", "Whistle", "Steam whistle", "Mechanisms", "Ratchet, pawl", "Clock", "Tick", "Tick-tock", "Gears", "Pulleys", "Sewing machine", "Mechanical fan", "Air conditioning", "Cash register", "Printer", "Camera", "Single-lens reflex camera", "Tools", "Hammer", "Jackhammer", "Sawing", "Filing (rasp)", "Sanding", "Power tool", "Drill", "Explosion", "Gunshot, gunfire", "Machine gun", "Fusillade", "Artillery fire", "Cap gun", "Fireworks", "Firecracker", "Burst, pop", "Eruption", "Boom", "Wood", "Chop", "Splinter", "Crack", "Glass", "Chink, clink", "Shatter", "Liquid", "Splash, splatter", "Slosh", "Squish", "Drip", "Pour", "Trickle, dribble", "Gush", "Fill (with liquid)", "Spray", "Pump (liquid)", "Stir", "Boiling", "Sonar", "Arrow", "Whoosh, swoosh, swish", "Thump, thud", "Thunk", "Electronic tuner", "Effects unit", "Chorus effect", "Basketball bounce", "Bang", "Slap, smack", "Whack, thwack", "Smash, crash", "Breaking", "Bouncing", "Whip", "Flap", "Scratch", "Scrape", "Rub", "Roll", "Crushing", "Crumpling, crinkling", "Tearing", "Beep, bleep", "Ping", "Ding", "Clang", "Squeal", "Creak", "Rustle", "Whir", "Clatter", "Sizzle", "Clicking", "Clickety-clack", "Rumble", "Plop", "Jingle, tinkle", "Hum", "Zing", "Boing", "Crunch", "Silence", "Sine wave", "Harmonic", "Chirp tone", "Sound effect", "Pulse", "Inside, small room", "Inside, large room or hall", "Inside, public space", "Outside, urban or manmade", "Outside, rural or natural", "Reverberation", "Echo", "Noise", "Environmental noise", "Static", "Mains hum", "Distortion", "Sidetone", "Cacophony", "White noise", "Pink noise", "Throbbing", "Vibration", "Television", "Radio", "Field recording"] \ No newline at end of file diff --git a/staticfiles/vite/assets/audio-preprocessor-B6FBlKED.js b/staticfiles/vite/assets/audio-preprocessor-B6FBlKED.js new file mode 100644 index 0000000..4bb69fd --- /dev/null +++ b/staticfiles/vite/assets/audio-preprocessor-B6FBlKED.js @@ -0,0 +1 @@ +class u{static async prepare(d,{signal:o}={}){if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");console.log("[BoomCast][YAMNet] Preparing local classification.");const i=window.AudioContext||window.webkitAudioContext;if(!i||!(window.OfflineAudioContext||window.webkitOfflineAudioContext))throw new Error("Browser audio decoding unavailable");const a=new i;try{const e=await a.decodeAudioData(await d.arrayBuffer());if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");if(!e.duration||!Number.isFinite(e.duration))throw new Error("Invalid audio duration");const c=window.OfflineAudioContext||window.webkitOfflineAudioContext,t=new c(1,Math.ceil(e.duration*16e3),16e3),r=t.createBufferSource();r.buffer=e,r.connect(t.destination),r.start();const w=await t.startRendering();if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");const n=w.getChannelData(0).slice();return console.log("[BoomCast][YAMNet] Waveform prepared.",{sampleRate:16e3,samples:n.length,durationSeconds:n.length/16e3}),n}finally{await a.close().catch(()=>{})}}}export{u as AudioPreprocessor}; diff --git a/staticfiles/vite/assets/browser-submission-gate-D8pBYGfs.js b/staticfiles/vite/assets/browser-submission-gate-D8pBYGfs.js new file mode 100644 index 0000000..d04ddab --- /dev/null +++ b/staticfiles/vite/assets/browser-submission-gate-D8pBYGfs.js @@ -0,0 +1 @@ +class w{static evaluate(c,s){var l,h;console.log("[BoomCast][Gate] Evaluating browser classification.");const n=new Set((s.whitelist||[]).map(e=>e.toLowerCase())),r=new Set((s.privacy_sensitive_speech||[]).map(e=>e.toLowerCase())),m=Number(((l=s.thresholds)==null?void 0:l.relevance)??.5),i=Number(((h=s.thresholds)==null?void 0:h.speech)??.5),t=c.filter(e=>n.has(e.class.toLowerCase())&&e.score>=m),o=c.some(e=>r.has(e.class.toLowerCase())&&e.score>=i);console.log("[BoomCast][Gate] Relevant whitelist matches:",t),console.log("[BoomCast][Gate] Speech detected:",o);const a=t.length?"whitelist_match":o?"speech_only":"no_match";return console.log(`[BoomCast][Gate] Decision: ${a.toUpperCase()}`),a!=="whitelist_match"&&console.log("[BoomCast][Gate] Automatic upload suppressed."),{result:a,speechDetected:o,matches:t}}}export{w as BrowserSubmissionGate}; diff --git a/staticfiles/vite/assets/browser-yamnet-classifier-B0-o1OkE.js b/staticfiles/vite/assets/browser-yamnet-classifier-B0-o1OkE.js new file mode 100644 index 0000000..411f519 --- /dev/null +++ b/staticfiles/vite/assets/browser-yamnet-classifier-B0-o1OkE.js @@ -0,0 +1 @@ +import{_}from"./frontend/src/entries/fireworks-home.js-CWybHvkC.js";/* empty css */import"./theme-DXAi27ON.js";const e="[BoomCast][YAMNet]";class v{static async classify(d,{modelUrl:b,classMapUrl:C,signal:o,loadTensorFlow:y}={}){let r,l,c,s;const M=performance.now();try{if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");if(console.log(`${e} Lazy-loading TensorFlow.js.`),r=y?await y():await _(()=>import("./index-jWGXPN38.js"),[]),o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");console.log(`${e} TensorFlow.js loaded.`),await r.ready(),console.log(`${e} Backend:`,r.getBackend()),console.log(`${e} Loading model.`);const[t,A]=await Promise.all([r.loadGraphModel(b),fetch(C,{cache:"force-cache",signal:o})]);if(l=t,!A.ok)throw new Error("YAMNet class map unavailable");const n=await A.json();if(!Array.isArray(n)||n.length!==521)throw new Error("Invalid YAMNet class map");if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");console.log(`${e} Model ready.`);const $=d.length<15600?Float32Array.from({length:15600},(a,i)=>d[i]||0):d;c=r.tensor1d($,"float32"),console.log(`${e} Starting inference.`);const m=await l.executeAsync(c);s=Array.isArray(m)?m:[m];const f=s.find(a=>a.shape.length===2&&a.shape[1]===n.length);if(!f)throw new Error("YAMNet score output unavailable");const g=await f.data();if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");const B=f.shape[0],w=n.map((a,i)=>{let h=-1,u=0;for(let p=0;ph&&(h=E,u=p)}return{class:a,score:h,frame:u,timeSeconds:Number((u*.48).toFixed(2))}});return w.sort((a,i)=>i.score-a.score),console.log(`${e} Inference completed in`,Math.round(performance.now()-M),"ms."),console.groupCollapsed(`${e} Top local predictions`),console.table(w.slice(0,10)),console.groupEnd(),w}catch(t){throw console.error(`${e} Local inference failed:`,t),t}finally{r&&console.log(`${e} TensorFlow memory before cleanup:`,r.memory()),console.log("[BoomCast][Cleanup] Disposing YAMNet tensors."),c==null||c.dispose(),s==null||s.forEach(t=>t==null?void 0:t.dispose()),console.log("[BoomCast][Cleanup] Disposing browser YAMNet model."),l==null||l.dispose(),console.log("[BoomCast][Cleanup] Releasing waveform buffers."),r&&console.log(`${e} TensorFlow memory after cleanup:`,r.memory()),console.log("[BoomCast][Cleanup] Browser classification cleanup complete.")}}}export{v as BrowserYamnetClassifier}; diff --git a/staticfiles/vite/assets/browser-yamnet-classifier-LqENBwVW.js b/staticfiles/vite/assets/browser-yamnet-classifier-LqENBwVW.js new file mode 100644 index 0000000..ae6cebe --- /dev/null +++ b/staticfiles/vite/assets/browser-yamnet-classifier-LqENBwVW.js @@ -0,0 +1 @@ +import{_}from"./frontend/src/entries/fireworks-home.js-DJ8Fx1Pi.js";/* empty css */import"./theme-DXAi27ON.js";const e="[BoomCast][YAMNet]";class v{static async classify(d,{modelUrl:b,classMapUrl:C,signal:o,loadTensorFlow:y}={}){let r,l,c,s;const M=performance.now();try{if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");if(console.log(`${e} Lazy-loading TensorFlow.js.`),r=y?await y():await _(()=>import("./index-jWGXPN38.js"),[]),o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");console.log(`${e} TensorFlow.js loaded.`),await r.ready(),console.log(`${e} Backend:`,r.getBackend()),console.log(`${e} Loading model.`);const[t,A]=await Promise.all([r.loadGraphModel(b),fetch(C,{cache:"force-cache",signal:o})]);if(l=t,!A.ok)throw new Error("YAMNet class map unavailable");const n=await A.json();if(!Array.isArray(n)||n.length!==521)throw new Error("Invalid YAMNet class map");if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");console.log(`${e} Model ready.`);const $=d.length<15600?Float32Array.from({length:15600},(a,i)=>d[i]||0):d;c=r.tensor1d($,"float32"),console.log(`${e} Starting inference.`);const m=await l.executeAsync(c);s=Array.isArray(m)?m:[m];const f=s.find(a=>a.shape.length===2&&a.shape[1]===n.length);if(!f)throw new Error("YAMNet score output unavailable");const g=await f.data();if(o!=null&&o.aborted)throw new DOMException("Cancelled","AbortError");const B=f.shape[0],w=n.map((a,i)=>{let h=-1,u=0;for(let p=0;ph&&(h=E,u=p)}return{class:a,score:h,frame:u,timeSeconds:Number((u*.48).toFixed(2))}});return w.sort((a,i)=>i.score-a.score),console.log(`${e} Inference completed in`,Math.round(performance.now()-M),"ms."),console.groupCollapsed(`${e} Top local predictions`),console.table(w.slice(0,10)),console.groupEnd(),w}catch(t){throw console.error(`${e} Local inference failed:`,t),t}finally{r&&console.log(`${e} TensorFlow memory before cleanup:`,r.memory()),console.log("[BoomCast][Cleanup] Disposing YAMNet tensors."),c==null||c.dispose(),s==null||s.forEach(t=>t==null?void 0:t.dispose()),console.log("[BoomCast][Cleanup] Disposing browser YAMNet model."),l==null||l.dispose(),console.log("[BoomCast][Cleanup] Releasing waveform buffers."),r&&console.log(`${e} TensorFlow memory after cleanup:`,r.memory()),console.log("[BoomCast][Cleanup] Browser classification cleanup complete.")}}}export{v as BrowserYamnetClassifier}; diff --git a/staticfiles/vite/assets/ffmpeg-video-extractor-BV766fGq.js b/staticfiles/vite/assets/ffmpeg-video-extractor-BV766fGq.js new file mode 100644 index 0000000..10823b9 --- /dev/null +++ b/staticfiles/vite/assets/ffmpeg-video-extractor-BV766fGq.js @@ -0,0 +1 @@ +import{_ as p}from"./frontend/src/entries/fireworks-home.js-CWybHvkC.js";/* empty css */import"./theme-DXAi27ON.js";const t="[BoomCast][FFmpeg]";class r extends Error{constructor(e,d){super(e,{cause:d}),this.name="VideoExtractionError",this.code=e}}async function A(i,{signal:e,onState:d=()=>{},createFFmpeg:v}={}){var y;let o,_=!1,f=!1,l="module_load_failed";const $=performance.now(),u="input",w="audio.wav",s=()=>o==null?void 0:o.terminate();e==null||e.addEventListener("abort",s,{once:!0}),console.log(`${t} Video input detected.`,{mimeType:i.type,sizeBytes:i.size});try{if(e!=null&&e.aborted)throw new r("cancelled");d("loading_ffmpeg"),console.log(`${t} Starting lazy import.`);const a=await(v||(async()=>{const[{FFmpeg:m},{default:E},{default:x}]=await Promise.all([p(()=>import("./index-Cr8NHl2n.js"),[]),p(()=>import("./ffmpeg-core-CTa1UqMt.js"),[]),p(()=>import("./ffmpeg-core-DJ3ydieg.js"),[])]);return console.log(`${t} ffmpeg.wasm module imported.`),{ffmpeg:new m,coreURL:E,wasmURL:x}}))();if(o=a.ffmpeg,e!=null&&e.aborted)throw new r("cancelled");if((y=o.on)==null||y.call(o,"log",({message:m})=>console.log(`${t}[core]`,m)),l="core_load_failed",console.log(`${t} Loading FFmpeg core.`),await o.load({coreURL:a.coreURL,wasmURL:a.wasmURL}),console.log(`${t} FFmpeg core ready.`),e!=null&&e.aborted)throw new r("cancelled");if(d("extracting_audio"),l="resource_failed",console.log(`${t} Writing input to virtual filesystem.`),_=!0,await o.writeFile(u,new Uint8Array(await i.arrayBuffer())),e!=null&&e.aborted)throw new r("cancelled");if(l="extraction_failed",console.log(`${t} Starting audio extraction: mono / 16kHz WAV.`),f=!0,await o.exec(["-i",u,"-vn","-ac","1","-ar","16000","-c:a","pcm_s16le",w])!==0)throw new r("invalid_media");if(e!=null&&e.aborted)throw new r("cancelled");const n=await o.readFile(w);if(!(n!=null&&n.byteLength))throw new r("invalid_media");if(n.byteLength>25*1024*1024)throw new r("output_too_large");const h=new File([n],`${i.name.replace(/\.[^.]+$/,"")||"recording"}.wav`,{type:"audio/wav"});return console.log(`${t} Audio extraction completed.`,{outputSizeBytes:h.size}),console.log(`${t} Extraction finished in ${Math.round(performance.now()-$)} ms.`),h}catch(c){const a=e!=null&&e.aborted?"cancelled":c instanceof r?c.code:c instanceof RangeError?"resource_failed":l;throw a==="invalid_media"&&console.warn(`${t} Unsupported or undecodable video.`),console.error(`${t} Audio extraction failed:`,c),new r(a,c)}finally{console.log(`${t} Removing temporary files.`),o!=null&&o.loaded&&(_&&await o.deleteFile(u).catch(()=>{}),f&&await o.deleteFile(w).catch(()=>{})),console.log(`${t} Terminating worker.`),o==null||o.terminate(),o=null,e==null||e.removeEventListener("abort",s),console.log(`${t} Cleanup complete.`)}}export{r as VideoExtractionError,A as extractVideoAudio}; diff --git a/staticfiles/vite/assets/ffmpeg-video-extractor-D9t31bt4.js b/staticfiles/vite/assets/ffmpeg-video-extractor-D9t31bt4.js new file mode 100644 index 0000000..12e663f --- /dev/null +++ b/staticfiles/vite/assets/ffmpeg-video-extractor-D9t31bt4.js @@ -0,0 +1 @@ +import{_ as p}from"./frontend/src/entries/fireworks-home.js-DJ8Fx1Pi.js";/* empty css */import"./theme-DXAi27ON.js";const t="[BoomCast][FFmpeg]";class r extends Error{constructor(e,d){super(e,{cause:d}),this.name="VideoExtractionError",this.code=e}}async function A(i,{signal:e,onState:d=()=>{},createFFmpeg:v}={}){var y;let o,_=!1,f=!1,l="module_load_failed";const $=performance.now(),u="input",w="audio.wav",s=()=>o==null?void 0:o.terminate();e==null||e.addEventListener("abort",s,{once:!0}),console.log(`${t} Video input detected.`,{mimeType:i.type,sizeBytes:i.size});try{if(e!=null&&e.aborted)throw new r("cancelled");d("loading_ffmpeg"),console.log(`${t} Starting lazy import.`);const a=await(v||(async()=>{const[{FFmpeg:m},{default:E},{default:x}]=await Promise.all([p(()=>import("./index-Cr8NHl2n.js"),[]),p(()=>import("./ffmpeg-core-CTa1UqMt.js"),[]),p(()=>import("./ffmpeg-core-DJ3ydieg.js"),[])]);return console.log(`${t} ffmpeg.wasm module imported.`),{ffmpeg:new m,coreURL:E,wasmURL:x}}))();if(o=a.ffmpeg,e!=null&&e.aborted)throw new r("cancelled");if((y=o.on)==null||y.call(o,"log",({message:m})=>console.log(`${t}[core]`,m)),l="core_load_failed",console.log(`${t} Loading FFmpeg core.`),await o.load({coreURL:a.coreURL,wasmURL:a.wasmURL}),console.log(`${t} FFmpeg core ready.`),e!=null&&e.aborted)throw new r("cancelled");if(d("extracting_audio"),l="resource_failed",console.log(`${t} Writing input to virtual filesystem.`),_=!0,await o.writeFile(u,new Uint8Array(await i.arrayBuffer())),e!=null&&e.aborted)throw new r("cancelled");if(l="extraction_failed",console.log(`${t} Starting audio extraction: mono / 16kHz WAV.`),f=!0,await o.exec(["-i",u,"-vn","-ac","1","-ar","16000","-c:a","pcm_s16le",w])!==0)throw new r("invalid_media");if(e!=null&&e.aborted)throw new r("cancelled");const n=await o.readFile(w);if(!(n!=null&&n.byteLength))throw new r("invalid_media");if(n.byteLength>25*1024*1024)throw new r("output_too_large");const h=new File([n],`${i.name.replace(/\.[^.]+$/,"")||"recording"}.wav`,{type:"audio/wav"});return console.log(`${t} Audio extraction completed.`,{outputSizeBytes:h.size}),console.log(`${t} Extraction finished in ${Math.round(performance.now()-$)} ms.`),h}catch(c){const a=e!=null&&e.aborted?"cancelled":c instanceof r?c.code:c instanceof RangeError?"resource_failed":l;throw a==="invalid_media"&&console.warn(`${t} Unsupported or undecodable video.`),console.error(`${t} Audio extraction failed:`,c),new r(a,c)}finally{console.log(`${t} Removing temporary files.`),o!=null&&o.loaded&&(_&&await o.deleteFile(u).catch(()=>{}),f&&await o.deleteFile(w).catch(()=>{})),console.log(`${t} Terminating worker.`),o==null||o.terminate(),o=null,e==null||e.removeEventListener("abort",s),console.log(`${t} Cleanup complete.`)}}export{r as VideoExtractionError,A as extractVideoAudio}; diff --git a/staticfiles/vite/assets/fireworks-home-9V5xwwGP.css b/staticfiles/vite/assets/fireworks-home-9V5xwwGP.css new file mode 100644 index 0000000..1f62f5e --- /dev/null +++ b/staticfiles/vite/assets/fireworks-home-9V5xwwGP.css @@ -0,0 +1 @@ +:root{--ink: #eaf0ff;--muted: #9caed1;--surface: #111a31;--surface-2: #17223e;--line: #2a3a61;--blue: #6aa8ff;--violet: #a78bfa;--fire: #ffb454;--danger: #ff727c;--success: #6ee7b7}*{box-sizing:border-box}body{min-width:320px;min-height:100vh;margin:0;color:var(--ink);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;background:radial-gradient(circle at 10% 0%,#263a76 0,transparent 30rem),radial-gradient(circle at 90% 20%,#4d236c 0,transparent 28rem),#090e1d}.shell{width:min(100% - 2.5rem,70rem);margin:0 auto;padding:clamp(2rem,6vw,5rem) 0}.brand{display:flex;align-items:center;gap:.75rem;font-size:.9rem;font-weight:800;letter-spacing:.11em;text-transform:uppercase}.intro{max-width:45rem}.kicker{margin:0 0 .8rem;color:#bfdbfe;font-size:.78rem;font-weight:800;letter-spacing:.15em;text-transform:uppercase}h1{max-width:12ch;margin:0;font-size:clamp(2.6rem,7vw,5.75rem);line-height:.96;letter-spacing:-.065em}.lede{max-width:38rem;margin:1.5rem 0 2.5rem;color:var(--muted);font-size:clamp(1rem,2vw,1.18rem);line-height:1.65}.upload-card,.results-card{border:1px solid var(--line);border-radius:1.5rem;background:linear-gradient(145deg,#162240d9,#0e162bdd);box-shadow:0 1.5rem 4rem #02061680;-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px)}.upload-card{padding:clamp(1rem,3vw,1.5rem)}.drop-zone{display:grid;min-height:16rem;place-items:center;padding:2rem;border:1.5px dashed #5d75aa;border-radius:1rem;cursor:pointer;text-align:center;background:linear-gradient(135deg,#1b2a4e80,#291c4b66);transition:.2s ease}.drop-zone:hover,.drop-zone.dragging{border-color:var(--blue);transform:translateY(-2px);background:#203360a8}.drop-zone:focus-within{outline:3px solid #6aa8ff66;outline-offset:3px}.file-input{width:.1px;height:.1px;position:absolute;opacity:0;overflow:hidden}.drop-zone .upload-icon{display:grid;width:4rem;aspect-ratio:1;place-items:center;margin:0 auto 1rem;border-radius:50%;color:#dbeafe;font-size:1.8rem;background:#4777c94d}.drop-zone .upload-icon__content{position:relative;z-index:1;margin:0;color:inherit;font-size:inherit;font-weight:850}.audio-upload--uploading .upload-icon,.audio-upload--processing .upload-icon,.audio-upload--success .upload-icon,.audio-upload--error .upload-icon{position:relative;width:5.5rem;margin-bottom:.25rem;color:#fff;font-size:1.25rem;box-shadow:0 0 0 .35rem #334e8d70,0 .6rem 2rem #101a3fa6}.audio-upload--uploading .upload-icon{background:conic-gradient(#91baff var(--upload-progress, 0%),#334b82 0)}.audio-upload--processing .upload-icon{background:#405caa}.audio-upload--processing .upload-icon:after{content:"";position:absolute;top:-.42rem;right:-.42rem;bottom:-.42rem;left:-.42rem;border:3px solid #9fc5ff;border-right-color:transparent;border-radius:50%;animation:spin 1.5s linear infinite}.audio-upload--success .upload-icon{background:#147d6c}.audio-upload--error .upload-icon{background:#9d385b}.audio-upload--uploading .drop-zone,.audio-upload--processing .drop-zone{border-color:#7296d5;background:linear-gradient(135deg,#18284c,#242046)}.audio-upload--uploading .drop-zone strong,.audio-upload--processing .drop-zone strong,.audio-upload--uploading .drop-zone>span>span:not(.upload-icon),.audio-upload--processing .drop-zone>span>span:not(.upload-icon),.audio-upload--uploading .file-name,.audio-upload--processing .file-name{opacity:.35}.audio-upload--uploading .drop-zone,.audio-upload--processing .drop-zone{cursor:default}.audio-upload--uploading .drop-zone:hover,.audio-upload--processing .drop-zone:hover{transform:none}.upload-cancel[hidden]{display:none}#classification-results{scroll-margin-top:1.5rem}@media(prefers-reduced-motion:reduce){.audio-upload--processing .upload-icon:after{animation:none}.audio-upload--uploading .drop-zone,.audio-upload--processing .drop-zone,.audio-upload--uploading .upload-icon,.audio-upload--processing .upload-icon{transition:none}}.drop-zone strong{display:block;font-size:1.15rem}.drop-zone span{display:block;margin-top:.4rem;color:var(--muted);font-size:.92rem}.file-name{min-height:1.3rem;margin:1rem 0 0;color:#c7d2fe;font-size:.9rem;overflow-wrap:anywhere}.form-footer{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:.9rem .25rem 0}.file-note{margin:0;color:var(--muted);font-size:.8rem}button,.button{text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:.6rem;border:0;border-radius:.8rem;padding:.85rem 1.15rem;cursor:pointer;color:#10172c;font:inherit;font-weight:800;background:linear-gradient(135deg,#93c5fd,#c4b5fd);box-shadow:0 .5rem 1.25rem #8b5cf640;transition:transform .2s ease,filter .2s ease}button:hover,.button:hover{transform:translateY(-1px);filter:brightness(1.08)}button:disabled{cursor:wait;filter:saturate(.4);transform:none}.spinner{width:1rem;height:1rem;border:2px solid #263253;border-top-color:currentColor;border-radius:50%;animation:spin .75s linear infinite}.htmx-indicator{display:none}.htmx-request.htmx-indicator{display:inline-block}.upload-form.htmx-request button{pointer-events:none}#upload-status{min-height:1.4rem;margin:1rem .25rem 0;color:#c7d2fe;font-size:.9rem}.upload-form.htmx-request+#upload-status{color:#fcd34d}#classification-results{margin-top:1.5rem}.results-card{padding:clamp(1.25rem,3vw,2rem);animation:reveal .35s ease-out}.result-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem}.result-heading h2{margin:0;font-size:clamp(1.4rem,3vw,2rem);letter-spacing:-.04em}.result-heading p{margin:.3rem 0 0;color:var(--muted)}.result-status{padding:.4rem .65rem;border-radius:999px;color:#a7f3d0;font-size:.75rem;font-weight:800;white-space:nowrap;background:#065f464d}.meta{display:flex;flex-wrap:wrap;gap:.6rem;margin:1.5rem 0}.meta span,.legend span{padding:.4rem .65rem;border:1px solid var(--line);border-radius:999px;color:#bdc9e5;font-size:.8rem;background:#101a31}.legend{display:flex;flex-wrap:wrap;gap:.5rem;margin:0 0 1.25rem}.legend .firework{color:#ffd18c;border-color:#c7721e80}.legend .speech{color:#ffadb4;border-color:#d5485880}.topbar{display:flex;align-items:center;justify-content:space-between;gap:1rem;margin-bottom:3.5rem}.brand{display:flex;align-items:center;gap:.7rem;color:var(--ink);font-size:.9rem;font-weight:800;letter-spacing:.1em;text-decoration:none;text-transform:uppercase}.brand-mark{display:grid;width:2.25rem;aspect-ratio:1;place-items:center;border-radius:.75rem;color:#141022;background:linear-gradient(135deg,#fcd34d,#fb7185);box-shadow:0 .5rem 1.5rem #fb718550}.nav{display:flex;gap:.35rem;padding:.25rem;border:1px solid var(--line);border-radius:.75rem;background:#111a31a6}.nav a{padding:.5rem .75rem;border-radius:.5rem;color:var(--muted);font-size:.86rem;font-weight:700;text-decoration:none}.nav a[aria-current=page]{color:var(--ink);background:#2a3b67}.result-grid{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(18rem,.75fr);gap:1.25rem}.result-group{padding:1.1rem;border:1px solid var(--line);border-radius:1rem;background:#0b1225a8}.result-group h3{margin:0 0 1rem;font-size:1rem}.prediction-list{display:grid;gap:.75rem;margin:0;padding:0;list-style:none}.prediction{--accent-color: #7799dd;position:relative;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem .75rem;align-items:center;padding:.7rem .75rem;overflow:hidden;border:1px solid #26365b;border-left:3px solid var(--accent-color);border-radius:.7rem;background:#121c34}.prediction--firework{--accent-color: var(--fire);background:linear-gradient(90deg,#7a421d55,#121c34)}.prediction--speech{--accent-color: var(--danger);background:linear-gradient(90deg,#6c213055,#121c34)}.prediction-label{min-width:0;font-weight:700;overflow-wrap:anywhere}.prediction-score{color:#c4d1ed;font-size:.85rem;font-variant-numeric:tabular-nums}.score-bar{grid-column:1/-1;height:.3rem;overflow:hidden;border-radius:999px;background:#263657}.score-bar i{display:block;width:calc(var(--score) * 1%);height:100%;border-radius:inherit;background:var(--accent-color)}.peak-list{display:grid;gap:.7rem}.peak-item{padding-bottom:.7rem;border-bottom:1px solid #253453}.peak-item:last-child{padding-bottom:0;border-bottom:0}.peak-time{color:#a9bce0;font-size:.78rem}.peak-item .prediction{margin-top:.35rem}.empty{margin:0;color:var(--muted)}.error-card{border-color:#a43d4d;background:linear-gradient(135deg,#4b1724dd,#1a1427dd)}.error-card h2,.error-card p{color:#fecdd3}@keyframes spin{to{transform:rotate(360deg)}}@keyframes reveal{0%{opacity:0;transform:translateY(.75rem)}}@media(max-width:42rem){.shell{width:min(100% - 1.25rem,70rem)}.form-footer,.result-heading{align-items:stretch;flex-direction:column}.form-footer button{width:100%}.result-grid{grid-template-columns:1fr}.result-status{align-self:flex-start}}@media(prefers-reduced-motion:reduce){*,:before,:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}.browser-gate{margin:1rem 0;padding:1rem;border:1px solid #e5bb7a;border-radius:.75rem;background:#4d392950}.browser-gate[hidden]{display:none}.browser-gate p{margin:.45rem 0 1rem}.browser-gate-actions{display:flex;gap:.65rem;flex-wrap:wrap}.browser-gate-actions button{cursor:pointer} diff --git a/staticfiles/vite/assets/frontend/src/entries/dashboard.js-CLKbAPGJ.js b/staticfiles/vite/assets/frontend/src/entries/dashboard.js-CLKbAPGJ.js new file mode 100644 index 0000000..fd71305 --- /dev/null +++ b/staticfiles/vite/assets/frontend/src/entries/dashboard.js-CLKbAPGJ.js @@ -0,0 +1 @@ +/* empty css */import"./fireworks-home.js-DJ8Fx1Pi.js";import"./map.js-jpUFFpF3.js";import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js"; diff --git a/staticfiles/vite/assets/frontend/src/entries/dashboard.js-Dizlz6Sl.js b/staticfiles/vite/assets/frontend/src/entries/dashboard.js-Dizlz6Sl.js new file mode 100644 index 0000000..b4fc849 --- /dev/null +++ b/staticfiles/vite/assets/frontend/src/entries/dashboard.js-Dizlz6Sl.js @@ -0,0 +1 @@ +/* empty css */import"./fireworks-home.js-CWybHvkC.js";import"./map.js-jpUFFpF3.js";import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js"; diff --git a/staticfiles/vite/assets/frontend/src/entries/fireworks-home.js-CWybHvkC.js b/staticfiles/vite/assets/frontend/src/entries/fireworks-home.js-CWybHvkC.js new file mode 100644 index 0000000..ba110ee --- /dev/null +++ b/staticfiles/vite/assets/frontend/src/entries/fireworks-home.js-CWybHvkC.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ffmpeg-video-extractor-BV766fGq.js","assets/theme-DXAi27ON.js","assets/theme-CHgv-U5K.css","assets/fireworks-navigation-B0T7du8_.css","assets/browser-yamnet-classifier-B0-o1OkE.js"])))=>i.map(i=>d[i]); +/* empty css */import"../../../theme-DXAi27ON.js";const j="modulepreload",H=function(o){return"/static/vite/"+o},z={},D=function(r,t,S){let s=Promise.resolve();if(t&&t.length>0){let c=function(d){return Promise.all(d.map(b=>Promise.resolve(b).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),m=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));s=c(t.map(d=>{if(d=H(d),d in z)return;z[d]=!0;const b=d.endsWith(".css"),u=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const g=document.createElement("link");if(g.rel=b?"stylesheet":j,b||(g.as="script"),g.crossOrigin="",g.href=d,m&&g.setAttribute("nonce",m),document.head.appendChild(g),b)return new Promise((k,f)=>{g.addEventListener("load",k),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function C(c){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=c,window.dispatchEvent(i),!i.defaultPrevented)throw c}return s.then(c=>{for(const i of c||[])i.status==="rejected"&&C(i.reason);return r().catch(C)})},F="[BoomCast][BrowserBeta]";function J(){const o=document.querySelector("#boomcast-browser-config");if(!o)return{browserProcessingBeta:!1};try{return JSON.parse(o.textContent)}catch(r){return console.error(`${F} Configuration unavailable:`,r),{browserProcessingBeta:!1}}}class P{constructor(r=J(),t=null,S={}){this.config=r,this.extractVideo=t,this.dependencies=S}isEnabled(){return this.config.browserProcessingBeta===!0}canProcess(r){return this.isEnabled()&&!!r&&(/^audio\//.test(r.type)||P.isVideo(r))}static isVideo(r){return!!r&&(r.type.startsWith("video/")||!r.type&&/\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(r.name||""))}async prepare(r,{signal:t,onState:S=()=>{}}={}){if(!this.canProcess(r))return{file:r,metadata:null,gate:"unavailable"};console.log(`${F} Initialising beta submission pipeline.`),console.log(`${F} File selected:`,{type:(r==null?void 0:r.type)||"",size:(r==null?void 0:r.size)||0});const s=P.isVideo(r),C=new AbortController,c=()=>C.abort();t==null||t.addEventListener("abort",c,{once:!0});const i=setTimeout(()=>C.abort(),5e3);let m;try{const u=await fetch(this.config.policyUrl,{cache:"no-store",credentials:"same-origin",signal:C.signal});if(!u.ok)throw new Error(`Policy HTTP ${u.status}`);if(m=await u.json(),!m.browser_processing_beta_enabled||m.version!==this.config.policyVersion)return console.log(`${F} Browser beta disabled or policy changed; using legacy submission flow.`),{file:r,metadata:null,gate:"unavailable"}}catch(u){if(t!=null&&t.aborted||(console.error(`${F} Policy unavailable:`,u),s))throw u;return{file:r,metadata:null,gate:"unavailable"}}finally{clearTimeout(i),t==null||t.removeEventListener("abort",c)}if(t!=null&&t.aborted)throw new DOMException("Cancelled","AbortError");let d=r;s&&(d=await(this.extractVideo||(await D(async()=>{const{extractVideoAudio:g}=await import("../../../ffmpeg-video-extractor-BV766fGq.js");return{extractVideoAudio:g}},__vite__mapDeps([0,1,2,3]))).extractVideoAudio)(r,{signal:t,onState:S}));const b={browser_processing_used:s,browser_processing_version:m.version,browser_gate_result:"unavailable",browser_override:!1};try{S("checking");let g=await(this.dependencies.prepareAudio||(await D(async()=>{const{AudioPreprocessor:k}=await import("../../../audio-preprocessor-B6FBlKED.js");return{AudioPreprocessor:k}},[])).AudioPreprocessor.prepare)(d,{signal:t});if(t!=null&&t.aborted)throw new DOMException("Cancelled","AbortError");try{const f=await(this.dependencies.classify||(await D(async()=>{const{BrowserYamnetClassifier:v}=await import("../../../browser-yamnet-classifier-B0-o1OkE.js");return{BrowserYamnetClassifier:v}},__vite__mapDeps([4,1,2,3]))).BrowserYamnetClassifier.classify)(g,{modelUrl:m.model_url,classMapUrl:m.class_map_url,signal:t});if(t!=null&&t.aborted)throw new DOMException("Cancelled","AbortError");const V=(this.dependencies.evaluate||(await D(async()=>{const{BrowserSubmissionGate:v}=await import("../../../browser-submission-gate-D8pBYGfs.js");return{BrowserSubmissionGate:v}},[])).BrowserSubmissionGate.evaluate)(f,m);return b.browser_processing_used=!0,b.browser_gate_result=V.result,b.browser_speech_detected=V.speechDetected,{file:d,metadata:b,gate:V.result,predictions:f.slice(0,5)}}finally{g=null,console.log("[BoomCast][Cleanup] Releasing waveform buffers.")}}catch(u){if(t!=null&&t.aborted)throw u;return console.error("[BoomCast][YAMNet] Local classification unavailable:",u),console.log("[BoomCast][Gate] Falling back to server classification."),b.browser_gate_result="unavailable",{file:d,metadata:b,gate:"unavailable"}}}cleanup(){console.log("[BoomCast][Cleanup] Browser beta resources released.")}}const l=document.querySelector(".upload-form");if(l){let E=function(e,{progress:n=null,message:h=""}={}){for(const p of V)l.classList.toggle(`audio-upload--${p}`,p===e);const a=e==="uploading"||e==="processing";_=a,c.disabled=a,t.disabled=a,i.hidden=!a,a?l.setAttribute("aria-busy","true"):l.removeAttribute("aria-busy"),e==="uploading"?(s.setAttribute("role","progressbar"),s.setAttribute("aria-label",o.uploadingAudio||"Uploading audio"),s.setAttribute("aria-valuemin","0"),s.setAttribute("aria-valuemax","100"),n===null?(s.removeAttribute("aria-valuenow"),s.setAttribute("aria-valuetext",o.uploadingAudio||"Uploading audio"),C.textContent="↑"):(s.setAttribute("aria-valuenow",String(n)),s.setAttribute("aria-valuetext",`${o.uploadingAudio||"Uploading audio"}: ${n}%`),s.style.setProperty("--upload-progress",`${n}%`),C.textContent=`${n}%`),f.textContent=n===null?o.uploadingAudio||"Uploading audio…":""):(s.removeAttribute("role"),s.removeAttribute("aria-label"),s.removeAttribute("aria-valuemin"),s.removeAttribute("aria-valuemax"),s.removeAttribute("aria-valuenow"),s.removeAttribute("aria-valuetext"),C.textContent=e==="processing"?"◉":e==="success"?"✓":e==="error"?"!":"↑",f.textContent=h||{processing:o.uploadCompleteAnalysing||"Upload complete. Analysing audio…",success:o.analysisComplete||"Analysis complete.",cancelled:o.uploadCancelled||"Upload cancelled."}[e]||"")},I=function(e){S.textContent=e?e.name:o.noFile||"No file selected",_||E(e?"file-selected":"idle"),e&&console.log("[boomcast-upload] file selected",{size:e.size,type:e.type})},O=function(e,n){clearTimeout(U),console.error("[boomcast-upload] upload failed",n),E("error",{message:e}),v=null},G=function(e){q||(q=!0,console.log("[boomcast-upload] upload complete, awaiting classifier"),U=window.setTimeout(()=>{v===e&&_&&E("processing")},120))},Y=function(e){var a,p;clearTimeout(U),v=null;let n;try{n=new DOMParser().parseFromString(e.responseText,"text/html")}catch(x){O(o.analysisFailed||"Analysis could not be completed.",x);return}const h=n.querySelector(".results-card");if(!h){O(o.analysisFailed||"Analysis could not be completed.",`Unexpected response (HTTP ${e.status})`);return}if(m.replaceChildren(document.importNode(h,!0)),(a=window.htmx)==null||a.process(m),e.status>=400||h.classList.contains("error-card")){const x=((p=h.querySelector("p"))==null?void 0:p.textContent)||o.analysisFailed||"Analysis could not be completed.";console.error("[boomcast-upload] classification failed",{status:e.status,message:x}),E("error",{message:x});return}console.log("[boomcast-upload] classification response received",e.status),E("success"),l.dataset.scrollToResults==="true"&&m.scrollIntoView({behavior:M.matches?"instant":"smooth",block:"start"})},N=function(e){if(B+=1,w==null||w.abort(),w=null,y=null,A=!1,L=!1,T=!1,d.hidden=!0,I(e),_||(c.disabled=!1,i.hidden=!0),!e||!R.canProcess(e))return;const n=B,h=new AbortController;w=h,A=!0,c.disabled=!0,i.hidden=!1,f.textContent=P.isVideo(e)?o.extractingAudio||"Extracting audio from video…":o.preparingRecording||"Preparing recording…",R.prepare(e,{signal:h.signal,onState:a=>{n===B&&(f.textContent=a==="checking"?o.checkingRecording||"Checking recording…":o.extractingAudio||"Extracting audio from video…")}}).then(a=>{if(!(n!==B||h.signal.aborted)){if(A=!1,i.hidden=!0,P.isVideo(e)&&a.file===e){L=!0,c.disabled=!0,f.textContent=o.videoExtractionFailed||"Could not extract audio from this video. Please choose an audio recording.";return}y=a,T=a.gate==="speech_only"||a.gate==="no_match",T?(b.textContent=a.gate==="speech_only"?o.speechGateTitle||"This recording appears to contain speech, but no relevant sound was detected.":o.irrelevantGateTitle||"No relevant sound was detected.",u.textContent=a.gate==="speech_only"?o.speechGateMessage||"To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review.":o.irrelevantGateMessage||"BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review.",d.hidden=!1,c.disabled=!0,f.textContent=o.gateChooseMessage||"Recording checked. Choose another recording or submit for manual review."):(c.disabled=!1,f.textContent=P.isVideo(e)?o.videoAudioOnly||"Video processed on this device. Only extracted audio will be sent if you submit.":o.readyToSubmit||"Ready to submit.")}}).catch(a=>{n===B&&(console.error("[BoomCast][BrowserBeta] Preparation failed:",a),A=!1,i.hidden=!0,P.isVideo(e)?(L=!0,c.disabled=!0,f.textContent=o.videoExtractionFailed||"Could not extract audio from this video. Please choose an audio recording."):(y={file:e,metadata:null,gate:"unavailable"},c.disabled=!1,f.textContent=o.readyToSubmit||"Ready to submit."))})},$=function(e,n=null){if(t.files[0]!==e)try{const p=new DataTransfer;if(p.items.add(e),t.files=p.files,t.files[0]!==e)throw new Error("Prepared audio could not replace video in form")}catch(p){console.error("[BoomCast][BrowserBeta] Could not secure native form upload:",p),L=!0,c.disabled=!0,f.textContent=o.secureVideoFailed||"Could not prepare this video for upload. Please choose an audio recording.";return}const h=new FormData(l);h.set("audio",e),n&&h.set("browser_processing_metadata",JSON.stringify(n));const a=new XMLHttpRequest;v=a,q=!1,m.replaceChildren(),E("uploading"),console.log("[boomcast-upload] upload started",{size:e.size,type:e.type}),a.open("POST",l.action),a.upload.addEventListener("progress",p=>{if(q||!p.lengthComputable||p.total<=0)return;const x=Math.min(100,Math.round(p.loaded/p.total*100));x!==Number(s.getAttribute("aria-valuenow"))&&(E("uploading",{progress:x}),console.log("[boomcast-upload] upload progress",x)),p.loaded>=p.total&&!q&&G(a)}),a.upload.addEventListener("load",()=>{G(a)}),a.addEventListener("load",()=>Y(a)),a.addEventListener("error",()=>O(o.uploadFailed||"Upload failed. Check your connection and try again.","Network error")),a.addEventListener("timeout",()=>O(o.uploadFailed||"Upload failed. Check your connection and try again.","Request timed out")),a.addEventListener("abort",()=>{clearTimeout(U),v=null,E("cancelled"),console.log("[boomcast-upload] upload cancelled")}),a.send(h)};const o=window.BOOMCAST_I18N||{},r=l.querySelector("#drop-zone"),t=l.querySelector("#audio-file"),S=l.querySelector("#file-name"),s=l.querySelector("#upload-progress-circle"),C=l.querySelector("#upload-icon-content"),c=l.querySelector('button[type="submit"]'),i=l.querySelector(".upload-cancel"),m=l.querySelector("#classification-results"),d=l.querySelector("#browser-gate"),b=l.querySelector("#browser-gate-title"),u=l.querySelector("#browser-gate-message"),g=l.querySelector("#browser-gate-choose"),k=l.querySelector("#browser-gate-override"),f=document.querySelector("#upload-status"),M=window.matchMedia("(prefers-reduced-motion: reduce)"),V=["idle","file-selected","uploading","processing","success","error","cancelled"];let v=null,_=!1,q=!1,U=null,B=0,w=null,y=null,A=!1,L=!1,T=!1;const R=new P;R.isEnabled()||console.log("[BoomCast][BrowserBeta] Feature disabled; using legacy submission flow."),t.addEventListener("change",()=>N(t.files[0])),["dragenter","dragover"].forEach(e=>r.addEventListener(e,n=>{n.preventDefault(),_||r.classList.add("dragging")})),["dragleave","drop"].forEach(e=>r.addEventListener(e,n=>{n.preventDefault(),r.classList.remove("dragging")})),r.addEventListener("drop",e=>{_||!e.dataTransfer.files.length||(t.files=e.dataTransfer.files,N(t.files[0]))}),l.addEventListener("submit",e=>{if(e.preventDefault(),e.stopImmediatePropagation(),_||A||L||T||!l.reportValidity())return;const n=t.files[0];if(n){if(y){$(y.file,y.metadata);return}if(!R.isEnabled()){$(n);return}$(n)}},!0),g.addEventListener("click",()=>t.click()),k.addEventListener("click",()=>{if(!T||!y||_||A)return;console.warn("[BoomCast][Gate] User explicitly overrode local gate."),console.log("[BoomCast][Gate] Submission will enter manual review.");const e={...y.metadata,browser_override:!0};y.metadata=e,T=!1,d.hidden=!0,$(y.file,e)}),i.addEventListener("click",()=>{A?(w==null||w.abort(),B+=1,A=!1,L=!0,c.disabled=!0,i.hidden=!0,f.textContent=o.extractionCancelled||o.preparationCancelled||"Preparation cancelled. Choose a recording to continue."):v==null||v.abort()}),window.addEventListener("pageshow",e=>{e.persisted&&(v==null||v.abort(),w==null||w.abort(),B+=1,y=null,A=!1,L=!1,T=!1,d.hidden=!0,c.disabled=!1,t.value="",m.replaceChildren(),I())})}export{D as _}; diff --git a/staticfiles/vite/assets/frontend/src/entries/fireworks-home.js-DJ8Fx1Pi.js b/staticfiles/vite/assets/frontend/src/entries/fireworks-home.js-DJ8Fx1Pi.js new file mode 100644 index 0000000..5b3ff29 --- /dev/null +++ b/staticfiles/vite/assets/frontend/src/entries/fireworks-home.js-DJ8Fx1Pi.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ffmpeg-video-extractor-D9t31bt4.js","assets/theme-DXAi27ON.js","assets/theme-CHgv-U5K.css","assets/fireworks-navigation-B0T7du8_.css","assets/browser-yamnet-classifier-LqENBwVW.js"])))=>i.map(i=>d[i]); +/* empty css */import"../../../theme-DXAi27ON.js";const j="modulepreload",H=function(r){return"/static/vite/"+r},z={},D=function(o,t,S){let s=Promise.resolve();if(t&&t.length>0){let c=function(d){return Promise.all(d.map(b=>Promise.resolve(b).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),m=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));s=c(t.map(d=>{if(d=H(d),d in z)return;z[d]=!0;const b=d.endsWith(".css"),u=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const g=document.createElement("link");if(g.rel=b?"stylesheet":j,b||(g.as="script"),g.crossOrigin="",g.href=d,m&&g.setAttribute("nonce",m),document.head.appendChild(g),b)return new Promise((k,f)=>{g.addEventListener("load",k),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function C(c){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=c,window.dispatchEvent(i),!i.defaultPrevented)throw c}return s.then(c=>{for(const i of c||[])i.status==="rejected"&&C(i.reason);return o().catch(C)})},F="[BoomCast][BrowserBeta]";function W(){const r=document.querySelector("#boomcast-browser-config");if(!r)return{browserProcessingBeta:!1};try{return JSON.parse(r.textContent)}catch(o){return console.error(`${F} Configuration unavailable:`,o),{browserProcessingBeta:!1}}}class _{constructor(o=W(),t=null,S={}){this.config=o,this.extractVideo=t,this.dependencies=S}isEnabled(){return this.config.browserProcessingBeta===!0}canProcess(o){return this.isEnabled()&&!!o&&(_.isAudio(o)||_.isVideo(o))}static isAudio(o){return!!o&&(o.type.startsWith("audio/")||!o.type&&/\.(aac|aif|aiff|flac|m4a|mp3|ogg|opus|wav|weba)$/i.test(o.name||""))}static isVideo(o){return!!o&&(o.type.startsWith("video/")||!o.type&&/\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(o.name||""))}async prepare(o,{signal:t,onState:S=()=>{}}={}){if(!this.canProcess(o))return{file:o,metadata:null,gate:"unavailable"};console.log(`${F} Initialising beta submission pipeline.`),console.log(`${F} File selected:`,{type:(o==null?void 0:o.type)||"",size:(o==null?void 0:o.size)||0});const s=_.isVideo(o),C=new AbortController,c=()=>C.abort();t==null||t.addEventListener("abort",c,{once:!0});const i=setTimeout(()=>C.abort(),5e3);let m;try{const u=await fetch(this.config.policyUrl,{cache:"no-store",credentials:"same-origin",signal:C.signal});if(!u.ok)throw new Error(`Policy HTTP ${u.status}`);if(m=await u.json(),!m.browser_processing_beta_enabled||m.version!==this.config.policyVersion)return console.log(`${F} Browser beta disabled or policy changed; using legacy submission flow.`),{file:o,metadata:null,gate:"unavailable"}}catch(u){if(t!=null&&t.aborted||(console.error(`${F} Policy unavailable:`,u),s))throw u;return{file:o,metadata:null,gate:"unavailable"}}finally{clearTimeout(i),t==null||t.removeEventListener("abort",c)}if(t!=null&&t.aborted)throw new DOMException("Cancelled","AbortError");let d=o;s&&(d=await(this.extractVideo||(await D(async()=>{const{extractVideoAudio:g}=await import("../../../ffmpeg-video-extractor-D9t31bt4.js");return{extractVideoAudio:g}},__vite__mapDeps([0,1,2,3]))).extractVideoAudio)(o,{signal:t,onState:S}));const b={browser_processing_used:s,browser_processing_version:m.version,browser_gate_result:"unavailable",browser_override:!1};try{S("checking");let g=await(this.dependencies.prepareAudio||(await D(async()=>{const{AudioPreprocessor:k}=await import("../../../audio-preprocessor-B6FBlKED.js");return{AudioPreprocessor:k}},[])).AudioPreprocessor.prepare)(d,{signal:t});if(t!=null&&t.aborted)throw new DOMException("Cancelled","AbortError");try{const f=await(this.dependencies.classify||(await D(async()=>{const{BrowserYamnetClassifier:v}=await import("../../../browser-yamnet-classifier-LqENBwVW.js");return{BrowserYamnetClassifier:v}},__vite__mapDeps([4,1,2,3]))).BrowserYamnetClassifier.classify)(g,{modelUrl:m.model_url,classMapUrl:m.class_map_url,signal:t});if(t!=null&&t.aborted)throw new DOMException("Cancelled","AbortError");const V=(this.dependencies.evaluate||(await D(async()=>{const{BrowserSubmissionGate:v}=await import("../../../browser-submission-gate-D8pBYGfs.js");return{BrowserSubmissionGate:v}},[])).BrowserSubmissionGate.evaluate)(f,m);return b.browser_processing_used=!0,b.browser_gate_result=V.result,b.browser_speech_detected=V.speechDetected,{file:d,metadata:b,gate:V.result,predictions:f.slice(0,5)}}finally{g=null,console.log("[BoomCast][Cleanup] Releasing waveform buffers.")}}catch(u){if(t!=null&&t.aborted)throw u;return console.error("[BoomCast][YAMNet] Local classification unavailable:",u),console.log("[BoomCast][Gate] Falling back to server classification."),b.browser_gate_result="unavailable",{file:d,metadata:b,gate:"unavailable"}}}cleanup(){console.log("[BoomCast][Cleanup] Browser beta resources released.")}}const l=document.querySelector(".upload-form");if(l){let x=function(e,{progress:n=null,message:h=""}={}){for(const p of V)l.classList.toggle(`audio-upload--${p}`,p===e);const a=e==="uploading"||e==="processing";E=a,c.disabled=a,t.disabled=a,i.hidden=!a,a?l.setAttribute("aria-busy","true"):l.removeAttribute("aria-busy"),e==="uploading"?(s.setAttribute("role","progressbar"),s.setAttribute("aria-label",r.uploadingAudio||"Uploading audio"),s.setAttribute("aria-valuemin","0"),s.setAttribute("aria-valuemax","100"),n===null?(s.removeAttribute("aria-valuenow"),s.setAttribute("aria-valuetext",r.uploadingAudio||"Uploading audio"),C.textContent="↑"):(s.setAttribute("aria-valuenow",String(n)),s.setAttribute("aria-valuetext",`${r.uploadingAudio||"Uploading audio"}: ${n}%`),s.style.setProperty("--upload-progress",`${n}%`),C.textContent=`${n}%`),f.textContent=n===null?r.uploadingAudio||"Uploading audio…":""):(s.removeAttribute("role"),s.removeAttribute("aria-label"),s.removeAttribute("aria-valuemin"),s.removeAttribute("aria-valuemax"),s.removeAttribute("aria-valuenow"),s.removeAttribute("aria-valuetext"),C.textContent=e==="processing"?"◉":e==="success"?"✓":e==="error"?"!":"↑",f.textContent=h||{processing:r.uploadCompleteAnalysing||"Upload complete. Analysing audio…",success:r.analysisComplete||"Analysis complete.",cancelled:r.uploadCancelled||"Upload cancelled."}[e]||"")},I=function(e){S.textContent=e?e.name:r.noFile||"No file selected",E||x(e?"file-selected":"idle"),e&&console.log("[boomcast-upload] file selected",{size:e.size,type:e.type})},O=function(e,n){clearTimeout(U),console.error("[boomcast-upload] upload failed",n),x("error",{message:e}),v=null},G=function(e){q||(q=!0,console.log("[boomcast-upload] upload complete, awaiting classifier"),U=window.setTimeout(()=>{v===e&&E&&x("processing")},120))},Y=function(e){var a,p;clearTimeout(U),v=null;let n;try{n=new DOMParser().parseFromString(e.responseText,"text/html")}catch(P){O(r.analysisFailed||"Analysis could not be completed.",P);return}const h=n.querySelector(".results-card");if(!h){O(r.analysisFailed||"Analysis could not be completed.",`Unexpected response (HTTP ${e.status})`);return}if(m.replaceChildren(document.importNode(h,!0)),(a=window.htmx)==null||a.process(m),e.status>=400||h.classList.contains("error-card")){const P=((p=h.querySelector("p"))==null?void 0:p.textContent)||r.analysisFailed||"Analysis could not be completed.";console.error("[boomcast-upload] classification failed",{status:e.status,message:P}),x("error",{message:P});return}console.log("[boomcast-upload] classification response received",e.status),x("success"),l.dataset.scrollToResults==="true"&&m.scrollIntoView({behavior:M.matches?"instant":"smooth",block:"start"})},N=function(e){if(B+=1,w==null||w.abort(),w=null,y=null,A=!1,L=!1,T=!1,d.hidden=!0,I(e),E||(c.disabled=!1,i.hidden=!0),!e||!R.canProcess(e))return;const n=B,h=new AbortController;w=h,A=!0,c.disabled=!0,i.hidden=!1,f.textContent=_.isVideo(e)?r.extractingAudio||"Extracting audio from video…":r.preparingRecording||"Preparing recording…",R.prepare(e,{signal:h.signal,onState:a=>{n===B&&(f.textContent=a==="checking"?r.checkingRecording||"Checking recording…":r.extractingAudio||"Extracting audio from video…")}}).then(a=>{if(!(n!==B||h.signal.aborted)){if(A=!1,i.hidden=!0,_.isVideo(e)&&a.file===e){L=!0,c.disabled=!0,f.textContent=r.videoExtractionFailed||"Could not extract audio from this video. Please choose an audio recording.";return}y=a,T=a.gate==="speech_only"||a.gate==="no_match",T?(b.textContent=a.gate==="speech_only"?r.speechGateTitle||"This recording appears to contain speech, but no relevant sound was detected.":r.irrelevantGateTitle||"No relevant sound was detected.",u.textContent=a.gate==="speech_only"?r.speechGateMessage||"To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review.":r.irrelevantGateMessage||"BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review.",d.hidden=!1,c.disabled=!0,f.textContent=r.gateChooseMessage||"Recording checked. Choose another recording or submit for manual review."):(c.disabled=!1,f.textContent=_.isVideo(e)?r.videoAudioOnly||"Video processed on this device. Only extracted audio will be sent if you submit.":r.readyToSubmit||"Ready to submit.")}}).catch(a=>{n===B&&(console.error("[BoomCast][BrowserBeta] Preparation failed:",a),A=!1,i.hidden=!0,_.isVideo(e)?(L=!0,c.disabled=!0,f.textContent=r.videoExtractionFailed||"Could not extract audio from this video. Please choose an audio recording."):(y={file:e,metadata:null,gate:"unavailable"},c.disabled=!1,f.textContent=r.readyToSubmit||"Ready to submit."))})},$=function(e,n=null){if(t.files[0]!==e)try{const p=new DataTransfer;if(p.items.add(e),t.files=p.files,t.files[0]!==e)throw new Error("Prepared audio could not replace video in form")}catch(p){console.error("[BoomCast][BrowserBeta] Could not secure native form upload:",p),L=!0,c.disabled=!0,f.textContent=r.secureVideoFailed||"Could not prepare this video for upload. Please choose an audio recording.";return}const h=new FormData(l);h.set("audio",e),n&&h.set("browser_processing_metadata",JSON.stringify(n));const a=new XMLHttpRequest;v=a,q=!1,m.replaceChildren(),x("uploading"),console.log("[boomcast-upload] upload started",{size:e.size,type:e.type}),a.open("POST",l.action),a.upload.addEventListener("progress",p=>{if(q||!p.lengthComputable||p.total<=0)return;const P=Math.min(100,Math.round(p.loaded/p.total*100));P!==Number(s.getAttribute("aria-valuenow"))&&(x("uploading",{progress:P}),console.log("[boomcast-upload] upload progress",P)),p.loaded>=p.total&&!q&&G(a)}),a.upload.addEventListener("load",()=>{G(a)}),a.addEventListener("load",()=>Y(a)),a.addEventListener("error",()=>O(r.uploadFailed||"Upload failed. Check your connection and try again.","Network error")),a.addEventListener("timeout",()=>O(r.uploadFailed||"Upload failed. Check your connection and try again.","Request timed out")),a.addEventListener("abort",()=>{clearTimeout(U),v=null,x("cancelled"),console.log("[boomcast-upload] upload cancelled")}),a.send(h)};const r=window.BOOMCAST_I18N||{},o=l.querySelector("#drop-zone"),t=l.querySelector("#audio-file"),S=l.querySelector("#file-name"),s=l.querySelector("#upload-progress-circle"),C=l.querySelector("#upload-icon-content"),c=l.querySelector('button[type="submit"]'),i=l.querySelector(".upload-cancel"),m=l.querySelector("#classification-results"),d=l.querySelector("#browser-gate"),b=l.querySelector("#browser-gate-title"),u=l.querySelector("#browser-gate-message"),g=l.querySelector("#browser-gate-choose"),k=l.querySelector("#browser-gate-override"),f=document.querySelector("#upload-status"),M=window.matchMedia("(prefers-reduced-motion: reduce)"),V=["idle","file-selected","uploading","processing","success","error","cancelled"];let v=null,E=!1,q=!1,U=null,B=0,w=null,y=null,A=!1,L=!1,T=!1;const R=new _;R.isEnabled()||console.log("[BoomCast][BrowserBeta] Feature disabled; using legacy submission flow."),t.addEventListener("change",()=>N(t.files[0])),["dragenter","dragover"].forEach(e=>o.addEventListener(e,n=>{n.preventDefault(),E||o.classList.add("dragging")})),["dragleave","drop"].forEach(e=>o.addEventListener(e,n=>{n.preventDefault(),o.classList.remove("dragging")})),o.addEventListener("drop",e=>{E||!e.dataTransfer.files.length||(t.files=e.dataTransfer.files,N(t.files[0]))}),l.addEventListener("submit",e=>{if(e.preventDefault(),e.stopImmediatePropagation(),E||A||L||T||!l.reportValidity())return;const n=t.files[0];if(n){if(y){$(y.file,y.metadata);return}if(!R.isEnabled()){$(n);return}$(n)}},!0),g.addEventListener("click",()=>t.click()),k.addEventListener("click",()=>{if(!T||!y||E||A)return;console.warn("[BoomCast][Gate] User explicitly overrode local gate."),console.log("[BoomCast][Gate] Submission will enter manual review.");const e={...y.metadata,browser_override:!0};y.metadata=e,T=!1,d.hidden=!0,$(y.file,e)}),i.addEventListener("click",()=>{A?(w==null||w.abort(),B+=1,A=!1,L=!0,c.disabled=!0,i.hidden=!0,f.textContent=r.extractionCancelled||r.preparationCancelled||"Preparation cancelled. Choose a recording to continue."):v==null||v.abort()}),window.addEventListener("pageshow",e=>{e.persisted&&(v==null||v.abort(),w==null||w.abort(),B+=1,y=null,A=!1,L=!1,T=!1,d.hidden=!0,c.disabled=!1,t.value="",m.replaceChildren(),I())})}export{D as _}; diff --git a/staticfiles/vite/assets/index-jWGXPN38.js b/staticfiles/vite/assets/index-jWGXPN38.js new file mode 100644 index 0000000..494a37f --- /dev/null +++ b/staticfiles/vite/assets/index-jWGXPN38.js @@ -0,0 +1,22435 @@ +function cI(n,e){for(var t=0;ts[r]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hI=1e-7,dI=1e-4;class lx{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class zd{refCount(e){return Qt("refCount")}incRef(e){return Qt("incRef")}timerAvailable(){return!0}time(e){return Qt("time")}read(e){return Qt("read")}readSync(e){return Qt("readSync")}readToGPU(e,t){return Qt("readToGPU")}numDataIds(){return Qt("numDataIds")}disposeData(e,t){return Qt("disposeData")}write(e,t,s){return Qt("write")}move(e,t,s,r,o){return Qt("move")}createTensorFromGPUData(e,t,s){return Qt("createTensorFromGPUData")}memory(){return Qt("memory")}floatPrecision(){return Qt("floatPrecision")}epsilon(){return this.floatPrecision()===32?hI:dI}dispose(){return Qt("dispose")}}function Qt(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Md(n){let e=n.length,t=0;for(;e>0;)t=Math.random()*e|0,e--,xs(n,e,t)}function pI(n,e){if(n.length!==e.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${n.length}Second array length was ${e.length}`);let t=n.length,s=0;for(;t>0;)s=Math.random()*t|0,t--,xs(n,t,s),xs(e,t,s)}function Ys(n,e,t){return Math.max(n,Math.min(e,t))}function uu(n){return n%2===0?n:n+1}function xs(n,e,t){const s=n[e];n[e]=n[t],n[t]=s}function ux(n){let e=0;for(let t=0;tt+` Shapes ${n} and ${e} must match`)}function qr(n){I(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function G(n){if(n.length===0)return 1;let e=n[0];for(let t=1;t0,t,s){return new Promise((r,o)=>{let a=0;const i=()=>{if(n()){r();return}a++;const l=e(a);if(t!=null&&a>=t){o();return}s!=null?s(i,l):setTimeout(i,l)};i()})}function Bd(n,e){let t=1,s=-1;for(let o=0;o=0)t*=n[o];else if(n[o]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${o}`);s=o}else if(n[o]<0)throw Error(`Shapes can not be < 0. Found ${n[o]} at dim ${o}`);if(s===-1){if(e>0&&e!==t)throw Error(`Size(${e}) must match the product of shape ${n}`);return n}if(t===0)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(e%t!==0)throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);const r=n.slice();return r[s]=e/t,r}function Se(n,e){const t=e.length;return n=n==null?e.map((s,r)=>r):[].concat(n),I(n.every(s=>s>=-t&&s`All values in axis param must be in range [-${t}, ${t}) but got axis ${n}`),I(n.every(s=>Rr(s)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(s=>s<0?t+s:s)}function Es(n,e){const t=[],s=[],r=e!=null&&Array.isArray(e)&&e.length===0,o=e==null||r?null:Se(e,n).sort();let a=0;for(let i=0;ii)&&n[i]===1&&(t.push(n[i]),s.push(i)),o[a]<=i&&a++}n[i]!==1&&(t.push(n[i]),s.push(i))}return{newShape:t,keptDims:s}}function wt(n,e){return tt(n,e)}function tt(n,e){let t=null;if(n==null||n==="float32")t=new Float32Array(e);else if(n==="int32")t=new Int32Array(e);else if(n==="bool")t=new Uint8Array(e);else if(n==="string")t=new Array(e);else throw new Error(`Unknown data type ${n}`);return t}function hx(n,e){for(let t=0;te+=t.length),e}function es(n){return typeof n=="string"||n instanceof String}function fx(n){return typeof n=="boolean"}function Dl(n){return typeof n=="number"}function Kr(n){return Array.isArray(n)?Kr(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":Dl(n)?"float32":es(n)?"string":fx(n)?"bool":"float32"}function Zs(n){return!!(n&&n.constructor&&n.call&&n.apply)}function Ol(n,e){for(let t=e;t=0;--s)t[s]=t[s+1]*n[s+1];return t}function mx(n,e,t,s=!1){const r=new Array;if(e.length===1){const o=e[0]*(s?2:1);for(let a=0;al*u)*(s?2:1);for(let l=0;lr*o)*(t?2:1);if(s===0)return[];if(s!==e.length)throw new Error(`[${n}] does not match the input size ${e.length}${t?" for a complex tensor":""}.`);return mx(0,n,e,t)}function gx(n,e){if(Array.isArray(n))return n;if(e==="float32")return n instanceof Float32Array?n:new Float32Array(n);if(e==="int32")return n instanceof Int32Array?n:new Int32Array(n);if(e==="bool"||e==="string")return Uint8Array.from(new Int32Array(n));throw new Error(`Unknown dtype ${e}`)}function cu(n,e){const t=Et(n,e);for(let s=0;ss*r,1);if(e==null||e==="float32")return bn(n,new Float32Array(t));if(e==="int32")return bn(n,new Int32Array(t));if(e==="bool")return bn(n,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function hn(n){n.forEach(e=>{I(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function Vn(n,e,t){if(e===0)return 0;if(e===1)return n[0];let s=n[n.length-1];for(let r=0;r"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;const e=this.getQueryParams(this.global.location.search);yy in e&&e[yy].split(",").forEach(s=>{const[r,o]=s.split(":");this.urlFlags[r]=$I(r,o)})}}function wI(n){const e={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...s)=>(vI(e,s[0],s[1]),s.join("="))),e}function vI(n,e,t){n[decodeURIComponent(e)]=decodeURIComponent(t||"")}function $I(n,e){const t=e.toLowerCase();return t==="true"||t==="false"?t==="true":`${+t}`===t?+t:e}function B(){return yx}let yx=null;function SI(n){yx=n}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let $h;function bx(){if($h==null){let n;if(typeof window<"u")n=window;else if(typeof global<"u")n=global;else if(typeof process<"u")n=process;else if(typeof self<"u")n=self;else throw new Error("Could not find a global object");$h=n}return $h}function II(){const n=bx();return n._tfGlobals==null&&(n._tfGlobals=new Map),n._tfGlobals}function Ud(n,e){const t=II();if(t.has(n))return t.get(n);{const s=e();return t.set(n,s),t.get(n)}}const hu="Abs",Oa="Acos",_a="Acosh",Ro="Add",du="AddN",Gd="All",Hd="Any",pu="ArgMax",fu="ArgMin",Fa="Asin",La="Asinh",Pa="Atan",za="Atanh",Ma="Atan2",mu="AvgPool",jd="AvgPoolGrad",gu="AvgPool3D",qd="AvgPool3DGrad",yu="BatchMatMul",bu="BatchToSpaceND",Kd="Bincount",xu="BitwiseAnd",NI="BroadcastTo",Xd="BroadcastArgs",Ba="Cast",Va="Ceil",Wa="ClipByValue",Yd="Complex",wu="ComplexAbs",vu="Concat",$u="Conv2D",Zd="Conv2DBackpropFilter",Su="Conv2DBackpropInput",Iu="Conv3D",Jd="Conv3DBackpropFilterV2",Qd="Conv3DBackpropInputV2",Ua="Cos",Ga="Cosh",ep="Cumprod",Nu="Cumsum",tp="CropAndResize",np="DenseBincount",sp="DepthToSpace",Cu="DepthwiseConv2dNative",rp="DepthwiseConv2dNativeBackpropFilter",op="DepthwiseConv2dNativeBackpropInput",ap="Diag",ku="Dilation2D",Vh="Dilation2DBackpropInput",Wh="Dilation2DBackpropFilter",ip="Draw",Ha="RealDiv",lp="Einsum",ja="Elu",up="EluGrad",qa="Erf",Tu="Equal",Ka="Exp",Eu="ExpandDims",Xa="Expm1",cp="FFT",hp="Fill",dp="FlipLeftRight",Ya="Floor",Za="FloorDiv",Au="FusedBatchNorm",Ru="GatherV2",pp="GatherNd",Du="Greater",Ja="GreaterEqual",Qa="Identity",fp="IFFT",mp="Imag",ei="IsFinite",ti="IsInf",ni="IsNan",Ou="LeakyRelu",_u="Less",Fu="LessEqual",gp="LinSpace",si="Log",ri="Log1p",Lu="LogicalAnd",Pu="LogicalNot",zu="LogicalOr",tJ="LogicalXor",CI="LogSoftmax",nJ="LowerBound",Mu="LRN",yp="LRNGrad",sJ="MatrixBandPart",Bu="Max",oi="Maximum",Vu="MaxPool",bp="MaxPoolGrad",Wu="MaxPool3D",xp="MaxPool3DGrad",wp="MaxPoolWithArgmax",Uu="Mean",Gu="Min",ai="Minimum",Hu="MirrorPad",ii="Mod",vp="Multinomial",li="Multiply",ju="Neg",qu="NotEqual",$p="NonMaxSuppressionV3",Sp="NonMaxSuppressionV4",Ip="NonMaxSuppressionV5",Ku="OnesLike",Xu="OneHot",Yu="Pack",Zu="PadV2",rJ="Pool",ui="Pow",Ju="Prelu",Qu="Prod",Np="RaggedGather",Cp="RaggedRange",kp="RaggedTensorToTensor",Tp="Range",Ep="Real",ci="Reciprocal",hi="Relu",ec="Reshape",tc="ResizeNearestNeighbor",Ap="ResizeNearestNeighborGrad",nc="ResizeBilinear",Rp="ResizeBilinearGrad",di="Relu6",sc="Reverse",pi="Round",fi="Rsqrt",Dp="ScatterNd",Op="TensorScatterUpdate",_p="SearchSorted",rc="Select",mi="Selu",oc="Slice",gi="Sin",yi="Sinh",bi="Sign",xi="Sigmoid",wi="Softplus",vi="Sqrt",ac="Sum",ic="SpaceToBatchND",lc="SplitV",uc="Softmax",Fp="SparseFillEmptyRows",Lp="SparseReshape",Pp="SparseSegmentMean",zp="SparseSegmentSum",Mp="SparseToDense",$i="SquaredDifference",Bp="Square",cc="StaticRegexReplace",Vp="StridedSlice",Wp="StringNGrams",Up="StringSplit",Gp="StringToHashBucketFast",Si="Sub",Ii="Tan",Ni="Tanh",Ci="Tile",Hp="TopK",jp="Transform",fo="Transpose",qp="Unique",hc="Unpack",dc="UnsortedSegmentSum",oJ="UpperBound",pc="ZerosLike",ki="Step",Uh="FromPixels",Kp="RotateWithOffset",_l="_FusedMatMul",Fl="FusedConv2D",Ll="FusedDepthwiseConv2D";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fn(...n){B().getBool("IS_TEST")||B().getBool("PROD")||console.warn(...n)}function kI(...n){B().getBool("IS_TEST")||B().getBool("PROD")||console.log(...n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xo=Ud("kernelRegistry",()=>new Map),ma=Ud("gradRegistry",()=>new Map);function Pl(n,e){const t=Yp(n,e);return xo.get(t)}function by(n){return ma.get(n)}function Gh(n){const e=xo.entries(),t=[];for(;;){const{done:s,value:r}=e.next();if(s)break;const[o,a]=r,[i]=o.split("_");i===n&&t.push(a)}return t}function Xp(n){const{kernelName:e,backendName:t}=n,s=Yp(e,t);xo.has(s)&&fn(`The kernel '${e}' for backend '${t}' is already registered`),xo.set(s,n)}function TI(n){const{kernelName:e}=n;ma.has(e)&&B().getBool("DEBUG")&&fn(`Overriding the gradient for '${e}'`),ma.set(e,n)}function aJ(n,e){const t=Yp(n,e);if(!xo.has(t))throw new Error(`The kernel '${n}' for backend '${e}' is not registered`);xo.delete(t)}function iJ(n){if(!ma.has(n))throw new Error(`The gradient '${n}' for backend is not registered`);ma.delete(n)}function lJ(n,e){Gh(n).forEach(s=>{const r=Object.assign({},s,{backendName:e});Xp(r)})}function Yp(n,e){return`${e}_${n}`}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xx(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}function EI(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function AI(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function s(){return this instanceof s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(s){var r=Object.getOwnPropertyDescriptor(n,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return n[s]}})}),t}var Sh,xy;function RI(){if(xy)return Sh;xy=1,Sh=e;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function e(T,S,_){this.low=T|0,this.high=S|0,this.unsigned=!!_}e.prototype.__isLong__,Object.defineProperty(e.prototype,"__isLong__",{value:!0});function t(T){return(T&&T.__isLong__)===!0}e.isLong=t;var s={},r={};function o(T,S){var _,P,V;return S?(T>>>=0,(V=0<=T&&T<256)&&(P=r[T],P)?P:(_=i(T,(T|0)<0?-1:0,!0),V&&(r[T]=_),_)):(T|=0,(V=-128<=T&&T<128)&&(P=s[T],P)?P:(_=i(T,T<0?-1:0,!1),V&&(s[T]=_),_))}e.fromInt=o;function a(T,S){if(isNaN(T))return S?b:y;if(S){if(T<0)return b;if(T>=f)return E}else{if(T<=-g)return A;if(T+1>=g)return C}return T<0?a(-T,S).neg():i(T%p|0,T/p|0,S)}e.fromNumber=a;function i(T,S,_){return new e(T,S,_)}e.fromBits=i;var l=Math.pow;function u(T,S,_){if(T.length===0)throw Error("empty string");if(T==="NaN"||T==="Infinity"||T==="+Infinity"||T==="-Infinity")return y;if(typeof S=="number"?(_=S,S=!1):S=!!S,_=_||10,_<2||36<_)throw RangeError("radix");var P;if((P=T.indexOf("-"))>0)throw Error("interior hyphen");if(P===0)return u(T.substring(1),S,_).neg();for(var V=a(l(_,8)),M=y,W=0;W>>0:this.low},k.toNumber=function(){return this.unsigned?(this.high>>>0)*p+(this.low>>>0):this.high*p+(this.low>>>0)},k.toString=function(S){if(S=S||10,S<2||36>>0,K=q.toString(S);if(W=U,W.isZero())return K+j;for(;K.length<6;)K="0"+K;j=""+K+j}},k.getHighBits=function(){return this.high},k.getHighBitsUnsigned=function(){return this.high>>>0},k.getLowBits=function(){return this.low},k.getLowBitsUnsigned=function(){return this.low>>>0},k.getNumBitsAbs=function(){if(this.isNegative())return this.eq(A)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,_=31;_>0&&(S&1<<_)==0;_--);return this.high!=0?_+33:_+1},k.isZero=function(){return this.high===0&&this.low===0},k.eqz=k.isZero,k.isNegative=function(){return!this.unsigned&&this.high<0},k.isPositive=function(){return this.unsigned||this.high>=0},k.isOdd=function(){return(this.low&1)===1},k.isEven=function(){return(this.low&1)===0},k.equals=function(S){return t(S)||(S=c(S)),this.unsigned!==S.unsigned&&this.high>>>31===1&&S.high>>>31===1?!1:this.high===S.high&&this.low===S.low},k.eq=k.equals,k.notEquals=function(S){return!this.eq(S)},k.neq=k.notEquals,k.ne=k.notEquals,k.lessThan=function(S){return this.comp(S)<0},k.lt=k.lessThan,k.lessThanOrEqual=function(S){return this.comp(S)<=0},k.lte=k.lessThanOrEqual,k.le=k.lessThanOrEqual,k.greaterThan=function(S){return this.comp(S)>0},k.gt=k.greaterThan,k.greaterThanOrEqual=function(S){return this.comp(S)>=0},k.gte=k.greaterThanOrEqual,k.ge=k.greaterThanOrEqual,k.compare=function(S){if(t(S)||(S=c(S)),this.eq(S))return 0;var _=this.isNegative(),P=S.isNegative();return _&&!P?-1:!_&&P?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},k.comp=k.compare,k.negate=function(){return!this.unsigned&&this.eq(A)?A:this.not().add(w)},k.neg=k.negate,k.add=function(S){t(S)||(S=c(S));var _=this.high>>>16,P=this.high&65535,V=this.low>>>16,M=this.low&65535,W=S.high>>>16,j=S.high&65535,U=S.low>>>16,q=S.low&65535,K=0,X=0,J=0,Q=0;return Q+=M+q,J+=Q>>>16,Q&=65535,J+=V+U,X+=J>>>16,J&=65535,X+=P+j,K+=X>>>16,X&=65535,K+=_+W,K&=65535,i(J<<16|Q,K<<16|X,this.unsigned)},k.subtract=function(S){return t(S)||(S=c(S)),this.add(S.neg())},k.sub=k.subtract,k.multiply=function(S){if(this.isZero())return y;if(t(S)||(S=c(S)),n){var _=n.mul(this.low,this.high,S.low,S.high);return i(_,n.get_high(),this.unsigned)}if(S.isZero())return y;if(this.eq(A))return S.isOdd()?A:y;if(S.eq(A))return this.isOdd()?A:y;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(m)&&S.lt(m))return a(this.toNumber()*S.toNumber(),this.unsigned);var P=this.high>>>16,V=this.high&65535,M=this.low>>>16,W=this.low&65535,j=S.high>>>16,U=S.high&65535,q=S.low>>>16,K=S.low&65535,X=0,J=0,Q=0,ne=0;return ne+=W*K,Q+=ne>>>16,ne&=65535,Q+=M*K,J+=Q>>>16,Q&=65535,Q+=W*q,J+=Q>>>16,Q&=65535,J+=V*K,X+=J>>>16,J&=65535,J+=M*q,X+=J>>>16,J&=65535,J+=W*U,X+=J>>>16,J&=65535,X+=P*K+V*q+M*U+W*j,X&=65535,i(Q<<16|ne,X<<16|J,this.unsigned)},k.mul=k.multiply,k.divide=function(S){if(t(S)||(S=c(S)),S.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var _=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,S.low,S.high);return i(_,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:y;var P,V,M;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return b;if(S.gt(this.shru(1)))return x;M=b}else{if(this.eq(A)){if(S.eq(w)||S.eq($))return A;if(S.eq(A))return w;var W=this.shr(1);return P=W.div(S).shl(1),P.eq(y)?S.isNegative()?w:$:(V=this.sub(S.mul(P)),M=P.add(V.div(S)),M)}else if(S.eq(A))return this.unsigned?b:y;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();M=y}for(V=this;V.gte(S);){P=Math.max(1,Math.floor(V.toNumber()/S.toNumber()));for(var j=Math.ceil(Math.log(P)/Math.LN2),U=j<=48?1:l(2,j-48),q=a(P),K=q.mul(S);K.isNegative()||K.gt(V);)P-=U,q=a(P,this.unsigned),K=q.mul(S);q.isZero()&&(q=w),M=M.add(q),V=V.sub(K)}return M},k.div=k.divide,k.modulo=function(S){if(t(S)||(S=c(S)),n){var _=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,S.low,S.high);return i(_,n.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},k.mod=k.modulo,k.rem=k.modulo,k.not=function(){return i(~this.low,~this.high,this.unsigned)},k.and=function(S){return t(S)||(S=c(S)),i(this.low&S.low,this.high&S.high,this.unsigned)},k.or=function(S){return t(S)||(S=c(S)),i(this.low|S.low,this.high|S.high,this.unsigned)},k.xor=function(S){return t(S)||(S=c(S)),i(this.low^S.low,this.high^S.high,this.unsigned)},k.shiftLeft=function(S){return t(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?i(this.low<>>32-S,this.unsigned):i(0,this.low<>>S|this.high<<32-S,this.high>>S,this.unsigned):i(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},k.shr=k.shiftRight,k.shiftRightUnsigned=function(S){if(t(S)&&(S=S.toInt()),S&=63,S===0)return this;var _=this.high;if(S<32){var P=this.low;return i(P>>>S|_<<32-S,_>>>S,this.unsigned)}else return S===32?i(_,0,this.unsigned):i(_>>>S-32,0,this.unsigned)},k.shru=k.shiftRightUnsigned,k.shr_u=k.shiftRightUnsigned,k.toSigned=function(){return this.unsigned?i(this.low,this.high,!1):this},k.toUnsigned=function(){return this.unsigned?this:i(this.low,this.high,!0)},k.toBytes=function(S){return S?this.toBytesLE():this.toBytesBE()},k.toBytesLE=function(){var S=this.high,_=this.low;return[_&255,_>>>8&255,_>>>16&255,_>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},k.toBytesBE=function(){var S=this.high,_=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,_>>>24,_>>>16&255,_>>>8&255,_&255]},e.fromBytes=function(S,_,P){return P?e.fromBytesLE(S,_):e.fromBytesBE(S,_)},e.fromBytesLE=function(S,_){return new e(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,_)},e.fromBytesBE=function(S,_){return new e(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],_)},Sh}var wx=RI();const vx=EI(wx),DI=cI({__proto__:null,default:vx},[wx]);/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vr=vx||DI;function Ti(n){return vr.fromString(n,!0,16)}const $x=Ti("c3a5c85c97cb3127"),wr=Ti("b492b66fbe98f273"),Vt=Ti("9ae16a3b2f90404f");function Hh(n){return n.xor(n.shru(47))}function Sx(n,e,t){const s=n.slice(e,e+t);return vr.fromBytes(Array.from(s),!0,!0)}function We(n,e){return Sx(n,e,8)}function wy(n,e){return Sx(n,e,4)}function yt(n,e){return e===0?n:n.shru(e).or(n.shl(64-e))}function js(n,e,t=Ti("9ddfea08eb382d69")){let s=n.xor(e).mul(t);s=s.xor(s.shru(47));let r=e.xor(s).mul(t);return r=r.xor(r.shru(47)),r=r.mul(t),r}function OI(n,e,t,s,r,o){r=r.add(n),o=yt(o.add(r).add(s),21);const a=r;return r=r.add(e),r=r.add(t),o=o.add(yt(r,44)),[r.add(s),o.add(a)]}function tl(n,e,t,s){return OI(We(n,e),We(n,e+8),We(n,e+16),We(n,e+24),t,s)}function _I(n,e=n.length){if(e>=8){const t=Vt.add(e*2),s=We(n,0).add(Vt),r=We(n,e-8),o=yt(r,37).mul(t).add(s),a=yt(s,25).add(r).mul(t);return js(o,a,t)}if(e>=4){const t=Vt.add(e*2),s=wy(n,0);return js(s.shl(3).add(e),wy(n,e-4),t)}if(e>0){const t=n[0],s=n[e>>1],r=n[e-1],o=t+(s<<8),a=e+(r<<2);return Hh(Vt.mul(o).xor($x.mul(a))).mul(Vt)}return Vt}function FI(n,e=n.length){const t=Vt.add(e*2),s=We(n,0).mul(wr),r=We(n,8),o=We(n,e-8).mul(t),a=We(n,e-16).mul(Vt);return js(yt(s.add(r),43).add(yt(o,30)).add(a),s.add(yt(r.add(Vt),18)).add(o),t)}function LI(n,e=n.length){const t=Vt.add(e*2),s=We(n,0).mul(Vt),r=We(n,8),o=We(n,e-8).mul(t),a=We(n,e-16).mul(Vt),i=yt(s.add(r),43).add(yt(o,30)).add(a),l=js(i,s.add(yt(r.add(Vt),18)).add(o),t),u=We(n,16).mul(t),c=We(n,24),h=i.add(We(n,e-32)).mul(t),d=l.add(We(n,e-24)).mul(t);return js(yt(u.add(c),43).add(yt(h,30)).add(d),u.add(yt(c.add(s),18)).add(h),t)}function Ix(n,e=n.length){const t=vr.fromNumber(81,!0);if(e<=32)return e<=16?_I(n,e):FI(n,e);if(e<=64)return LI(n,e);let s=t,r=t.mul(wr).add(113),o=Hh(r.mul(Vt).add(113)).mul(Vt),a=[vr.UZERO,vr.UZERO],i=[vr.UZERO,vr.UZERO];s=s.mul(Vt).add(We(n,0));let l=0;const u=(e-1>>6)*64,c=u+(e-1&63)-63;do s=yt(s.add(r).add(a[0]).add(We(n,l+8)),37).mul(wr),r=yt(r.add(a[1]).add(We(n,l+48)),42).mul(wr),s=s.xor(i[1]),r=r.add(a[0]).add(We(n,l+40)),o=yt(o.add(i[0]),33).mul(wr),a=tl(n,l,a[1].mul(wr),s.add(i[0])),i=tl(n,l+32,o.add(i[1]),r.add(We(n,l+16))),[o,s]=[s,o],l+=64;while(l!==u);const h=wr.add(o.and(255).shl(1));return l=c,i[0]=i[0].add(e-1&63),a[0]=a[0].add(i[0]),i[0]=i[0].add(a[0]),s=yt(s.add(r).add(a[0]).add(We(n,l+8)),37).mul(h),r=yt(r.add(a[1]).add(We(n,l+48)),42).mul(h),s=s.xor(i[1].mul(9)),r=r.add(a[0].mul(9).add(We(n,l+40))),o=yt(o.add(i[0]),33).mul(h),a=tl(n,l,a[1].mul(h),s.add(i[0])),i=tl(n,l+32,o.add(i[1]),r.add(We(n,l+16))),[o,s]=[s,o],js(js(a[0],i[0],h).add(Hh(r).mul($x)).add(o),js(a[1],i[1],h).add(s),h)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function As(n,e){return e==="string"?ns(n):ir([n],e)}function PI(n,e){return n instanceof Float32Array&&e==="float32"||n instanceof Int32Array&&e==="int32"||n instanceof Uint8Array&&e==="bool"}function ir(n,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=is(n)),B().getBool("DEBUG")&&hx(n,e),PI(n,e))return n;if(e==null||e==="float32"||e==="complex64")return new Float32Array(n);if(e==="int32")return new Int32Array(n);if(e==="bool"){const t=new Uint8Array(n.length);for(let s=0;s{r=s()};let a;const i=Nt();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(o);else{o();for(const u of r)u.dataSync();a=Promise.resolve({kernelMs:Nt()-i})}if(B().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let u=0;u{MI(h,c.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then(u=>u.kernelMs),extraInfo:a.then(u=>u.getExtraProfileInfo!=null?u.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:s,timeMs:r,inputs:o,extraInfo:a}=e;s.forEach(i=>{Promise.all([i.data(),r,a]).then(l=>{this.logger.logKernelProfile(t,i,l[0],l[1],o,l[2])})})}}function MI(n,e,t){if(e!=="float32")return!1;for(let s=0;s0?g:""} `}}console.log(`%c${l} %c${i} %c${u}D ${h} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VI(n,e,t){const s={},r={};for(let l=0;ls[g.id]=!0),p=!0,r[u.id]=!0;break}if(p)break}}const o={};o[t.id]=!0;const a={};for(let l=n.length-1;l>=0;l--){const u=n[l],c=u.inputs;for(let h=0;h=0;r--){const o=e[r],a=[];if(o.outputs.forEach(l=>{const u=n[l.id];u!=null?a.push(u):a.push(null)}),o.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const i=o.gradient(a);for(const l in o.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);const u=t(()=>i[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);const c=o.inputs[l];if(!Ce(u.shape,c.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);if(n[c.id]==null)n[c.id]=u;else{const h=n[c.id];n[c.id]=s(h,u),h.dispose()}}}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vy=20,Qo=3,Ih=7;function UI(n,e,t,s){const r=he(e),o=GI(n,e,t,r),a=e.length,i=gl(n,e,t,r,o),l=["Tensor"];return s&&(l.push(` dtype: ${t}`),l.push(` rank: ${a}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(i.map(u=>" "+u).join(` +`)),l.join(` +`)}function GI(n,e,t,s){const r=G(e),o=s[s.length-1],a=new Array(o).fill(0),i=e.length,l=t==="complex64"?oa(n):n;if(i>1)for(let u=0;uvy){const m=Qo*a;let y=Array.from(n.slice(0,m)),b=Array.from(n.slice((i-Qo)*a,i*a));return t==="complex64"&&(y=oa(y),b=oa(b)),["["+y.map((w,x)=>ra(w,r[x],t)).join(", ")+", ..., "+b.map((w,x)=>ra(w,r[i-Qo+x],t)).join(", ")+"]"]}return["["+(t==="complex64"?oa(n):Array.from(n)).map((m,y)=>ra(m,r[y],t)).join(", ")+"]"]}const u=e.slice(1),c=s.slice(1),h=s[0]*a,d=[];if(i>vy){for(let g=0;g0?d[0]+p:"");for(let g=1;g`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=s||tt(t,this.size),this.strides=he(e)}set(e,...t){t.length===0&&(t=[0]),I(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const s=this.locToIndex(t);this.values[s]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const o=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(o)}t++}let s=e[e.length-1];for(let r=0;rSs(s))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),zn().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=zn().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ss(t))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await zn().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),zn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return co.print(this,e)}clone(){return this.throwIfDisposed(),co.clone(this)}toString(e=!1){const t=this.dataSync();return UI(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),co.cast(this,e)}variable(e=!0,t,s){return this.throwIfDisposed(),zn().makeVariable(this,e,t,s)}}Object.defineProperty(Re,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});function H(){return Ud("Tensor",()=>Re)}H();class zl extends Re{constructor(e,t,s,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=s}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Ce(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);zn().disposeTensor(this),this.dataId=e.dataId,zn().incRef(this,null)}dispose(){zn().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(zl,Symbol.hasInstance,{value:n=>n instanceof Re&&n.assign!=null&&n.assign instanceof Function});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var $y;(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"})($y||($y={}));var jh;(function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"})(jh||(jh={}));var qh;(function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"})(qh||(qh={}));var Kh;(function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"})(Kh||(Kh={}));var Xh;(function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"})(Xh||(Xh={}));const qI={float32:Kh,int32:jh,bool:qh,complex64:Xh};function an(n,e){if(n==="string"||e==="string"){if(n==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${n} with ${e}`)}return qI[n][e]}function Zp(n){return an(n,"int32")}function kx(n){return n!=null&&typeof n=="object"&&"texture"in n&&n.texture instanceof WebGLTexture}function Tx(n){return typeof GPUBuffer<"u"&&n!=null&&typeof n=="object"&&"buffer"in n&&n.buffer instanceof GPUBuffer}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ze(n,e){if(n.dtype===e.dtype)return[n,e];const t=an(n.dtype,e.dtype);return[n.cast(t),e.cast(t)]}function Ex(n,e){I(n.dtype===e.dtype,()=>`The dtypes of the first(${n.dtype}) and second(${e.dtype}) input must match`)}function fc(n,e){return e.some(t=>t.id===n.id)}function Is(n){const e=[];return Ax(n,e,new Set),e}function Ax(n,e,t){if(n==null)return;if(n instanceof Re){e.push(n);return}if(!KI(n))return;const s=n;for(const r in s){const o=s[r];t.has(o)||(t.add(o),Ax(o,e,t))}}function KI(n){return Array.isArray(n)||typeof n=="object"}const cJ=Object.freeze(Object.defineProperty({__proto__:null,assertTypesMatch:Ex,getTensorsInContainer:Is,isTensorInList:fc,makeTypesMatch:Ze},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Nh(n){return n.kernelName!=null}class Sy{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class wo{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Sy}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Gh(e).forEach(s=>{s.disposeFunc!=null&&s.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const s=t.factory();if(s&&!(s instanceof zd)&&typeof s.then=="function"){const r=++this.pendingBackendInitId,o=s.then(a=>r(rthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(s),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,s){e();try{const r=s();return t(),r}catch(r){throw t(),r}}nextTensorId(){return wo.nextTensorId++}nextVariableId(){return wo.nextVariableId++}clone(e){const t=R.runKernel(Qa,{x:e}),s={x:e},r=a=>({x:()=>{const i="float32",l={x:a},u={dtype:i};return R.runKernel(Ba,l,u)}}),o=[];return this.addTapeNode(this.state.activeScope.name,s,[t],r,o,{}),t}runKernel(e,t,s){if(this.backendName==null&&this.backend,!(Pl(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:s})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,s){const r=this.backend.numDataIds();let o=0;s.forEach(l=>{o+=l.dtype==="complex64"?3:1});const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-t-o-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,s=[];const r=this.isTapeOn(),o=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let l;const u=Nh(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Nh(e)){const{kernelName:f,inputs:g,attrs:m}=e;this.backendName==null&&this.backend;const y=Pl(f,this.backendName);I(y!=null,()=>`Cannot find registered kernel '${f}' for backend '${this.backendName}'`),i=()=>{const b=this.backend.numDataIds();l=y.kernelFunc({inputs:g,attrs:m,backend:this.backend});const w=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(f,b,w);const x=w.map($=>$.rank!=null?$:this.makeTensorFromTensorInfo($));if(r){const $=this.getTensorsForGradient(f,g,x);s=this.saveTensorsForBackwardMode($)}return x}}else{const{forwardFunc:f}=e,g=m=>{r&&(s=m.map(y=>this.keep(this.clone(y))))};i=()=>{const m=this.backend.numDataIds();l=this.tidy(()=>f(this.backend,g));const y=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,m,y),y}}const{inputs:c,attrs:h}=e,d=Nh(e)?null:e.backwardsFunc;let p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(p=this.profiler.profileKernel(u,c,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),r&&this.addTapeNode(u,c,t,d,s,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-o,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(f=>c[f]!=null?c[f].shape:null),outputShapes:t.map(f=>f.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(s=>this.keep(this.clone(s)))}getTensorsForGradient(e,t,s){const r=by(e);if(r!=null){const o=r.inputsToSave||[],a=r.outputsToSave||[];let i;r.saveAllInputs?(I(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(u=>t[u])):i=o.map(u=>t[u]);const l=s.filter((u,c)=>a[c]);return i.concat(l)}return[]}makeTensor(e,t,s,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");s=s||"float32",r=r||this.backend;let o=e;s==="string"&&es(e[0])&&(o=e.map(l=>ns(l)));const a=r.write(o,t,s),i=new Re(t,s,a,this.nextTensorId());if(this.trackTensor(i,r),s==="string"){const l=this.state.tensorInfo.get(a),u=px(o);this.state.numBytes+=u-l.bytes,l.bytes=u}return i}makeTensorFromDataId(e,t,s,r){s=s||"float32";const o={dataId:e,shape:t,dtype:s};return this.makeTensorFromTensorInfo(o,r)}makeTensorFromTensorInfo(e,t){const{dataId:s,shape:r,dtype:o}=e,a=new Re(r,o,s,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,s,r){s=s||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));const o=new zl(e,t,s,this.nextTensorId());if(this.state.registeredVariables[o.name]!=null)throw new Error(`Variable with name ${o.name} was already registered`);return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let s=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(s=e.size*fa(e.dtype)),this.state.numBytes+=s,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:s})),e instanceof zl||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){const s=e.size*fa(e.dtype);this.state.numBytes-=s}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,s=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-s;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,s,r,o,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:s,saved:o},l=by(e);l!=null&&(r=l.gradFunc),r!=null&&(i.gradient=u=>(u=u.map((c,h)=>{if(c==null){const d=s[h],p=Et(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),r(u.length>1?u:u[0],o,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Is(e),s=new Set(t.map(o=>o.id));for(let o=0;o{!o.kept&&o.scopeId===r.id&&this.track(o)})}gradients(e,t,s,r=!1){if(I(t.length>0,()=>"gradients() received an empty list of xs."),s!=null&&s.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);const o=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));I(o instanceof Re,()=>"The result y returned by f() must be a tensor.");const a=VI(this.state.activeTape,t,o);if(!r&&a.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const i={};i[o.id]=s??XI(o.shape),WI(i,a,u=>this.tidy(u),YI);const l=t.map(u=>i[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(const c of u.saved)c.dispose()}),this.state.activeTape=null),{value:o,grads:l}})}customGrad(e){return I(Zs(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{I(t.every(i=>i instanceof Re),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let s;const r={};t.forEach((i,l)=>{r[l]=i});const o=(i,l)=>(s=e(...t,l),I(s.value instanceof Re,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),I(Zs(s.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),s.value),a=(i,l)=>{const u=s.gradFunc(i,l),c=Array.isArray(u)?u:[u];I(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),I(c.every(d=>d instanceof Re),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const h={};return c.forEach((d,p)=>{h[p]=()=>d}),h};return this.runKernelFunc({forwardFunc:o,backwardsFunc:a,inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Nt(),s=await this.backend.time(e);return s.wallMs=Nt()-t,s}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Sy;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}wo.nextTensorId=0;wo.nextVariableId=0;function XI(n){const e=cu(G(n),"float32");return R.makeTensor(e,n,"float32")}function Rx(){const n=bx();if(n._tfengine==null){const e=new xI(n);n._tfengine=new wo(e)}return SI(n._tfengine.ENV),HI(()=>n._tfengine),n._tfengine}const R=Rx();function YI(n,e){const t={a:n,b:e};return R.runKernel(Ro,t)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZI(){return typeof navigator<"u"&&navigator!=null}let Yh;function JI(n){Yh=n}function Jp(n){if(Yh!==void 0)return Yh;if(n||ZI()){if(n||(n=navigator),n.product==="ReactNative")return!0;const e=n.userAgent||n.vendor||(typeof window<"u"?window.opera:"");if(!e){const t=n;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}return!1}function Qp(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}const hJ=Object.freeze(Object.defineProperty({__proto__:null,isBrowser:Qp,isMobile:Jp,mockIsMobile:JI},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kt=B();Kt.registerFlag("DEBUG",()=>!1,n=>{n&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Kt.registerFlag("IS_BROWSER",()=>Qp());Kt.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u");Kt.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Kt.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));Kt.registerFlag("PROD",()=>!1);Kt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Kt.getBool("DEBUG"));Kt.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Kt.registerFlag("IS_TEST",()=>!1);Kt.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Kt.getBool("DEBUG"));Kt.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Kt.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Kt.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ls(n,e){let t=n;if(ut(n))return e==="string"?[]:[n.length];if(kx(n)){const r=n.channels||"RGBA";return[n.height,n.width*r.length]}else if(Tx(n))return[n.buffer.size/(e==null?4:fa(e))];if(!Array.isArray(n))return[];const s=[];for(;Array.isArray(t)||ut(t)&&e!=="string";)s.push(t.length),t=t[0];return Array.isArray(n)&&B().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Dx(n,s,[]),s}function Dx(n,e,t){if(t=t||[],!Array.isArray(n)&&!ut(n)){I(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}I(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${n.length} elements`),I(n.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${n.length} elements`);const s=e.slice(1);for(let r=0;r=0&&(r=s),Iy(s,r,e,t),n==null||!ut(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){const l=n==null?"null":n.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`)}const o=ls(n,r);!ut(n)&&!Array.isArray(n)&&(n=[n]);const i=r!=="string"?ir(n,r):is(n,[],!0);return R.makeTensor(i,o,r)}function ga(n,e,t,s="numeric"){if(!Array.isArray(n))throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``);return n.map((o,a)=>N(o,`${e}[${a}]`,t,s))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ox="__op";function D(n){const e=Object.keys(n);if(e.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let t=e[0];const s=n[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+Ox;const r=(...o)=>{R.startScope(t);try{const a=s(...o);return $s(a)&&console.error("Cannot return a Promise inside of tidy."),R.endScope(a),a}catch(a){throw R.endScope(null),a}};return Object.defineProperty(r,"name",{value:t,configurable:!0}),r}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QI(n,e){const t=N(n,"real","complex"),s=N(e,"imag","complex");Rt(t.shape,s.shape,`real and imag shapes, ${t.shape} and ${s.shape}, must match in call to tf.complex().`);const r={real:t,imag:s};return R.runKernel(Yd,r)}const Js=D({complex_:QI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lr(n,e,t,s){if(s==null)s=Kr(n);else if(s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Tx(n)||kx(n)){if(s!=="float32"&&s!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return R.backend.createTensorFromGPUData(n,e||t,s)}if(!ut(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(e!=null){hn(e);const r=G(e),o=G(t);I(r===o,()=>`Based on the provided shape, [${e}], the tensor should have ${r} values but has ${o}`);for(let a=0;a`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!ut(n)&&!Array.isArray(n)&&(n=[n]),e=e||t,n=s!=="string"?ir(n,s):is(n,[],!0),R.makeTensor(n,e,s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xn(n,e,t){const s=ls(n,t);return lr(n,e,s,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Dr={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class Kn{static join(e){return new Kn(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,e==null||(e instanceof Array||(e=[e]),e=e.map(s=>ut(s)?s.buffer:s),e.length===0))return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let s=0;s=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(r){return e=r.end?1:0}if(t(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;const s=eN(this.shards,t);return s===-1?-1:(this.previousShardIndex=s,this.previousShardIndex)}}function eN(n,e){let t=0,s=n.length;for(;t<=s;){const r=Math.floor((s-t)/2)+t,o=e(n[r]);if(o===0)return r;o<0?s=r:t=r+1}return-1}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dJ(){B().set("PROD",!0)}function pJ(){B().set("DEBUG",!0)}function fJ(){B().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function mJ(n){B().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function gJ(){R.disposeVariables()}function Yn(){return R}function Ny(){return R.memory()}function yJ(n){return R.profile(n)}function z(n,e){return R.tidy(n,e)}function be(n){Is(n).forEach(t=>t.dispose())}function bt(n){return R.keep(n)}function bJ(n){return R.time(n)}function xJ(n){return R.setBackend(n)}function wJ(){return R.ready()}function tN(){return R.backendName}function vJ(n){R.removeBackend(n)}function $J(n){return R.findBackend(n)}function SJ(n){return R.findBackendFactory(n)}function _x(n,e,t=1){return R.registerBackend(n,e,t)}function Fx(){return R.backend}function IJ(n,e){B().setPlatform(n,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qs=4;async function Zh(n,e){const t=[],s=[],r=Array.isArray(n)?n.map(a=>a.name):Object.keys(n);for(let a=0;a{const d=await l.bytes(),p=d.reduce((m,y)=>m+y.length,0)+Qs*d.length,f=new Uint8Array(p);let g=0;for(let m=0;mt.slice(r+i,r+l));s[o.name]=Lx(o,t.slice(r,r+a)),r+=a}return s}function nN(n,e){const t=G(n.shape);let s;if("quantization"in n){const r=n.quantization;s=Dr[r.dtype]}else if(n.dtype==="string"){let r=0;for(let o=0;o(r=await Cy(s,r,c),r.slice(u,c)));r=await Cy(s,r,a);const i=r.slice(0,a);r=r.slice(a);const l=Lx(o,i);if(t[o.name]=l,tN()==="webgpu"){const u=Fx();"uploadToGPU"in u&&G(l.shape)>=B().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&u.uploadToGPU(l.dataId)}}return t}function rN(n){if(n===null)throw new Error(`Invalid input value: ${JSON.stringify(n)}`);let e=0;const t=[];n.forEach(o=>{if(e+=o.byteLength,t.push(o.byteLength===o.buffer.byteLength?o:new o.constructor(o)),!(o instanceof Float32Array||o instanceof Int32Array||o instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${o.constructor.name}`)});const s=new Uint8Array(e);let r=0;return t.forEach(o=>{s.set(new Uint8Array(o.buffer),r),r+=o.byteLength}),s.buffer}const tf=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function ky(n){return tf?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function oN(n){if(tf)return Buffer.from(n).toString("base64");const e=new Uint8Array(n);let t="";for(let s=0,r=e.length;s{let s=t<<13,r=0;for(;(s&8388608)===0;)r-=8388608,s<<=1;return s&=-8388609,r+=947912704,s|r},e=new Uint32Array(2048);e[0]=0;for(let t=1;t<1024;t++)e[t]=n(t);for(let t=1024;t<2048;t++)e[t]=939524096+(t-1024<<13);return e}function lN(){const n=new Uint32Array(64);n[0]=0,n[31]=1199570944,n[32]=2147483648,n[63]=3347054592;for(let e=1;e<31;e++)n[e]=e<<23;for(let e=33;e<63;e++)n[e]=2147483648+(e-32<<23);return n}function uN(){const n=new Uint32Array(64);for(let e=0;e<64;e++)n[e]=1024;return n[0]=n[32]=0,n}function cN(){const n=iN(),e=lN(),t=uN();return s=>{const r=new ArrayBuffer(4*s.length),o=new Uint32Array(r);for(let a=0;a>10]+(i&1023)]+e[i>>10];o[a]=l}return new Float32Array(r)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Xe{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Xe.instance==null&&(Xe.instance=new Xe),Xe.instance}static registerSaveRouter(e){Xe.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Xe.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Xe.getHandlers(e,"save")}static getLoadHandlers(e,t){return Xe.getHandlers(e,"load",t)}static getHandlers(e,t,s){const r=[];return(t==="load"?Xe.getInstance().loadRouters:Xe.getInstance().saveRouters).forEach(a=>{const i=a(e,s);i!==null&&r.push(i)}),r}}const hN=n=>Xe.registerSaveRouter(n),dN=n=>Xe.registerLoadRouter(n),Bx=n=>Xe.getSaveHandlers(n),Vx=(n,e)=>Xe.getLoadHandlers(n,e);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jh="tensorflowjs",Qh=1,Nr="models_store",Ws="model_info_store";function Wx(){if(!B().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const n=typeof window>"u"?self:window,e=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function ed(n){const e=n.result;e.createObjectStore(Nr,{keyPath:"modelPath"}),e.createObjectStore(Ws,{keyPath:"modelPath"})}class Or{constructor(e){if(this.indexedDB=Wx(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((s,r)=>{const o=this.indexedDB.open(Jh,Qh);o.onupgradeneeded=()=>ed(o),o.onsuccess=()=>{const a=o.result;if(t==null){const i=a.transaction(Nr,"readonly"),u=i.objectStore(Nr).get(this.modelPath);u.onsuccess=()=>{if(u.result==null)return a.close(),r(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));s(u.result.modelArtifacts)},u.onerror=c=>(a.close(),r(u.error)),i.oncomplete=()=>a.close()}else{t.weightData=Kn.join(t.weightData);const i=Ei(t),l=a.transaction(Ws,"readwrite");let u=l.objectStore(Ws),c;try{c=u.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(d){return r(d)}let h;c.onsuccess=()=>{h=a.transaction(Nr,"readwrite");const d=h.objectStore(Nr);let p;try{p=d.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(f){return r(f)}p.onsuccess=()=>s({modelArtifactsInfo:i}),p.onerror=f=>{u=l.objectStore(Ws);const g=u.delete(this.modelPath);g.onsuccess=()=>(a.close(),r(p.error)),g.onerror=m=>(a.close(),r(p.error))}},c.onerror=d=>(a.close(),r(c.error)),l.oncomplete=()=>{h==null?a.close():h.oncomplete=()=>a.close()}}},o.onerror=a=>r(o.error)})}}Or.URL_SCHEME="indexeddb://";const Ux=n=>B().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Or.URL_SCHEME)?pN(n.slice(Or.URL_SCHEME.length)):null;Xe.registerSaveRouter(Ux);Xe.registerLoadRouter(Ux);function pN(n){return new Or(n)}function fN(n){return n.startsWith(Or.URL_SCHEME)?n.slice(Or.URL_SCHEME.length):n}class mN{constructor(){this.indexedDB=Wx()}async listModels(){return new Promise((e,t)=>{const s=this.indexedDB.open(Jh,Qh);s.onupgradeneeded=()=>ed(s),s.onsuccess=()=>{const r=s.result,o=r.transaction(Ws,"readonly"),i=o.objectStore(Ws).getAll();i.onsuccess=()=>{const l={};for(const u of i.result)l[u.modelPath]=u.modelArtifactsInfo;e(l)},i.onerror=l=>(r.close(),t(i.error)),o.oncomplete=()=>r.close()},s.onerror=r=>t(s.error)})}async removeModel(e){return e=fN(e),new Promise((t,s)=>{const r=this.indexedDB.open(Jh,Qh);r.onupgradeneeded=()=>ed(r),r.onsuccess=()=>{const o=r.result,a=o.transaction(Ws,"readwrite"),i=a.objectStore(Ws),l=i.get(e);let u;l.onsuccess=()=>{if(l.result==null)return o.close(),s(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const c=i.delete(e),h=()=>{u=o.transaction(Nr,"readwrite");const p=u.objectStore(Nr).delete(e);p.onsuccess=()=>t(l.result.modelArtifactsInfo),p.onerror=f=>s(l.error)};c.onsuccess=h,c.onerror=d=>(h(),o.close(),s(l.error))}},l.onerror=c=>(o.close(),s(l.error)),a.oncomplete=()=>{u==null?o.close():u.oncomplete=()=>o.close()}},r.onerror=o=>s(r.error)})}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ws="/",ho="tensorflowjs_models",Gx="info",gN="model_topology",yN="weight_specs",bN="weight_data",xN="model_metadata";function Hx(n){return{info:[ho,n,Gx].join(ws),topology:[ho,n,gN].join(ws),weightSpecs:[ho,n,yN].join(ws),weightData:[ho,n,bN].join(ws),modelMetadata:[ho,n,xN].join(ws)}}function jx(n){for(const e of Object.values(n))window.localStorage.removeItem(e)}function wN(n){const e=n.split(ws);if(e.length<3)throw new Error(`Invalid key format: ${n}`);return e.slice(1,e.length-1).join(ws)}function vN(n){return n.startsWith(_r.URL_SCHEME)?n.slice(_r.URL_SCHEME.length):n}class _r{constructor(e){if(!B().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Hx(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),s=JSON.stringify(e.weightSpecs),r=Ei(e),o=Kn.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,s),this.LS.setItem(this.keys.weightData,oN(o));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch{throw jx(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},s=JSON.parse(this.LS.getItem(this.keys.topology));if(s==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=s;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(r==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const o=this.LS.getItem(this.keys.modelMetadata);if(o!=null){const i=JSON.parse(o);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}const a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=aN(a),t}}_r.URL_SCHEME="localstorage://";const qx=n=>B().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(_r.URL_SCHEME)?$N(n.slice(_r.URL_SCHEME.length)):null;Xe.registerSaveRouter(qx);Xe.registerLoadRouter(qx);function $N(n){return new _r(n)}class SN{constructor(){I(B().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),I(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=ho+ws,s=ws+Gx;for(let r=0;r"scheme must not be undefined or null."),e.endsWith(mo)&&(e=e.slice(0,e.indexOf(mo))),I(e.length>0,()=>"scheme must not be an empty string.");const s=Bt.getInstance();I(s.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),s.managers[e]=t}static getManager(e){const t=Bt.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Bt.getInstance().managers)}}function yl(n){if(n.indexOf(mo)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Bt.getSchemes().join(",")}`);return{scheme:n.split(mo)[0],path:n.split(mo)[1]}}async function Kx(n,e,t=!1){I(n!==e,()=>`Old path and new path are the same: '${n}'`);const s=Xe.getLoadHandlers(n);I(s.length>0,()=>`Copying failed because no load handler is found for source URL ${n}.`),I(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${n}.`);const r=s[0],o=Xe.getSaveHandlers(e);I(o.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),I(o.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${e}.`);const a=o[0],i=yl(n).scheme,l=yl(n).path,u=i===yl(n).scheme,c=await r.load();t&&u&&await Bt.getManager(i).removeModel(l);const h=await a.save(c);return t&&!u&&await Bt.getManager(i).removeModel(l),h.modelArtifactsInfo}async function IN(){const n=Bt.getSchemes(),e={};for(const t of n){const s=await Bt.getManager(t).listModels();for(const r in s){const o=t+mo+r;e[o]=s[r]}}return e}async function NN(n){const e=yl(n);return Bt.getManager(e.scheme).removeModel(e.path)}async function CN(n,e){return Kx(n,e,!1)}async function kN(n,e){return Kx(n,e,!0)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class TN{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){if(typeof window>"u"||!B().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",s=>{if(s.source===window&&s.data.name===this.messageName){s.stopPropagation();const r=this.functionRefs[s.data.index];r(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(e){return xx(e)}}if(B().get("IS_BROWSER")){B().setPlatform("browser",new TN);try{Bt.registerManager(_r.URL_SCHEME,new SN)}catch{}try{Bt.registerManager(Or.URL_SCHEME,new mN)}catch{}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EN={importFetch:()=>require("node-fetch")};let Ch;class AN{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return B().global.fetch!=null?B().global.fetch(e,t):(Ch==null&&(Ch=EN.importFetch()),Ch(e,t))}now(){const e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}B().get("IS_NODE")&&!B().get("IS_BROWSER")&&B().setPlatform("node",new AN);/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ve(n,e="float32",t){return e=e||"float32",hn(n),new pt(n,e,t)}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RN(n,e){const t=N(n,"x","cast");if(!dx(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if(e==="string"&&t.dtype!=="string"||e!=="string"&&t.dtype==="string")throw new Error("Only strings can be casted to strings");const s={x:t},r={dtype:e};return R.runKernel(Ba,s,r)}const ee=D({cast_:RN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DN(n){const t={x:N(n,"x","clone","string_or_numeric")};return R.runKernel(Qa,t)}const vs=D({clone_:DN});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xx(n,e=!1){console.log(n.toString(e))}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */Rx();const ON={buffer:ve,cast:ee,clone:vs,print:Xx};jI(ON);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _N(n,e){let t=N(n,"a","add"),s=N(e,"b","add");[t,s]=Ze(t,s);const r={a:t,b:s};return R.runKernel(Ro,r)}const Y=D({add_:_N});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FN(n,e){let t=N(n,"a","floorDiv"),s=N(e,"b","floorDiv");[t,s]=Ze(t,s);const r={a:t,b:s};return R.runKernel(Za,r)}const rf=D({floorDiv_:FN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LN(n,e){let t=N(n,"a","div"),s=N(e,"b","div");if([t,s]=Ze(t,s),t.dtype==="int32"&&s.dtype==="int32")return rf(t,s);const r={a:t,b:s},o={};return R.runKernel(Ha,r,o)}const ce=D({div_:LN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PN(n,e){let t=N(n,"a","mul"),s=N(e,"b","mul");[t,s]=Ze(t,s);const r={a:t,b:s};return R.runKernel(li,r)}const O=D({mul_:PN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zN(n){const e=N(n,"x","abs");if(e.dtype==="complex64"){const t={x:e};return R.runKernel(wu,t)}else{const t={x:e};return R.runKernel(hu,t)}}const lt=D({abs_:zN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MN(n){const t={x:N(n,"x","acos")};return R.runKernel(Oa,t)}const Yx=D({acos_:MN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BN(n){const t={x:N(n,"x","acosh")};return R.runKernel(_a,t)}const Zx=D({acosh_:BN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VN(n){I(Array.isArray(n),()=>"The argument passed to tf.addN() must be a list of tensors"),I(n.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${n.length}`);const e=n.map((r,o)=>N(r,`tensors${o}`,"addN")),t=e[0];e.forEach(r=>{if(r.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(r=>{if(!Ce(r.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=e;return R.runKernel(du,s)}const WN=D({addN_:VN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UN(n,e=null,t=!1){const r={x:N(n,"x","all","bool")},o={axis:e,keepDims:t};return R.runKernel(Gd,r,o)}const of=D({all_:UN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GN(n,e=null,t=!1){const r={x:N(n,"x","any","bool")},o={axis:e,keepDims:t};return R.runKernel(Hd,r,o)}const Bl=D({any_:GN});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HN(n,e=0){const s={x:N(n,"x","argMax")},r={axis:e};return R.runKernel(pu,s,r)}const vo=D({argMax_:HN});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jN(n,e=0){const s={x:N(n,"x","argMin")},r={axis:e};return R.runKernel(fu,s,r)}const Jx=D({argMin_:jN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qN(n){const t={x:N(n,"x","asin")};return R.runKernel(Fa,t)}const Qx=D({asin_:qN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KN(n){const t={x:N(n,"x","asinh")};return R.runKernel(La,t)}const ew=D({asinh_:KN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XN(n){const t={x:N(n,"x","atan")};return R.runKernel(Pa,t)}const tw=D({atan_:XN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YN(n,e){let t=N(n,"a","atan2"),s=N(e,"b","atan2");[t,s]=Ze(t,s);const r={a:t,b:s};return R.runKernel(Ma,r)}const nw=D({atan2_:YN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZN(n){const t={x:N(n,"x","atanh")};return R.runKernel(za,t)}const sw=D({atanh_:ZN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ai(n,e,t,s,r="NHWC",o){const a=n[3],i=[...e,a],l=Ds(r);return $t(n,i,t,o,s,null,null,l)}function Dn(n,e,t,s,r,o,a="channelsLast"){const[i,l]=ya(e);let u;if(a==="channelsLast")u=[i,l,n[3],n[3]];else if(a==="channelsFirst")u=[i,l,n[1],n[1]];else throw new Error(`Unknown dataFormat ${a}`);return $t(n,u,t,s,r,o,!1,a)}function Rs(n,e,t,s,r,o,a="NDHWC"){const[i,l,u]=td(e);let c,h;if(a==="NDHWC")h="channelsLast",c=[i,l,u,n[4],n[4]];else if(a==="NCDHW")h="channelsFirst",c=[i,l,u,n[1],n[1]];else throw new Error(`Unknown dataFormat ${a}`);return ur(n,c,t,s,r,!1,h,o)}function $t(n,e,t,s,r,o,a=!1,i="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,h]=n;else if(i==="channelsFirst")[l,h,u,c]=n;else throw new Error(`Unknown dataFormat ${i}`);const[d,p,,f]=e,[g,m]=ya(t),[y,b]=ya(s),w=go(d,y),x=go(p,b),{padInfo:$,outHeight:C,outWidth:E}=eC(r,u,c,g,m,w,x,o,i),A=a?f*h:f;let k;return i==="channelsFirst"?k=[l,A,C,E]:i==="channelsLast"&&(k=[l,C,E,A]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:h,outHeight:C,outWidth:E,outChannels:A,padInfo:$,strideHeight:g,strideWidth:m,filterHeight:d,filterWidth:p,effectiveFilterHeight:w,effectiveFilterWidth:x,dilationHeight:y,dilationWidth:b,inShape:n,outShape:k,filterShape:e}}function ur(n,e,t,s,r,o=!1,a="channelsLast",i){let[l,u,c,h,d]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[l,u,c,h,d]=n;else if(a==="channelsFirst")[l,d,u,c,h]=n;else throw new Error(`Unknown dataFormat ${a}`);const[p,f,g,,m]=e,[y,b,w]=td(t),[x,$,C]=td(s),E=go(p,x),A=go(f,$),k=go(g,C),{padInfo:T,outDepth:S,outHeight:_,outWidth:P}=tC(r,u,c,h,y,b,w,E,A,k,i),V=o?m*d:m;let M;return a==="channelsFirst"?M=[l,V,S,_,P]:a==="channelsLast"&&(M=[l,S,_,P,V]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:h,inChannels:d,outDepth:S,outHeight:_,outWidth:P,outChannels:V,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:w,filterDepth:p,filterHeight:f,filterWidth:g,effectiveFilterDepth:E,effectiveFilterHeight:A,effectiveFilterWidth:k,dilationDepth:x,dilationHeight:$,dilationWidth:C,inShape:n,outShape:M,filterShape:e}}function JN(n,e,t,s,r){s==null&&(s=af(n,e,t));const o=n[0],a=n[1],i=ba((o-e+2*s)/t+1,r),l=ba((a-e+2*s)/t+1,r);return[i,l]}function QN(n,e,t,s,r,o){r==null&&(r=af(n,e[0],s[0]));const a=[0,0,0,t];for(let i=0;i<3;i++)n[i]+2*r>=e[i]&&(a[i]=ba((n[i]-e[i]+2*r)/s[i]+1,o));return a}function af(n,e,t,s=1){const r=go(e,s);return Math.floor((n[0]*(t-1)-t+r)/2)}function ya(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function td(n){return typeof n=="number"?[n,n,n]:n}function go(n,e){return e<=1?n:n+(n-1)*(e-1)}function eC(n,e,t,s,r,o,a,i,l){let u,c,h;if(typeof n=="number"){u={top:n,bottom:n,left:n,right:n,type:n===0?"VALID":"NUMBER"};const p=JN([e,t],o,s,n,i);c=p[0],h=p[1]}else if(n==="same"){c=Math.ceil(e/s),h=Math.ceil(t/r);const d=Math.max(0,(c-1)*s+o-e),p=Math.max(0,(h-1)*r+a-t),f=Math.floor(d/2),g=d-f,m=Math.floor(p/2),y=p-m;u={top:f,bottom:g,left:m,right:y,type:"SAME"}}else if(n==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-o+1)/s),h=Math.ceil((t-a+1)/r);else if(typeof n=="object"){const d=l==="channelsLast"?n[1][0]:n[2][0],p=l==="channelsLast"?n[1][1]:n[2][1],f=l==="channelsLast"?n[2][0]:n[3][0],g=l==="channelsLast"?n[2][1]:n[3][1];u={top:d,bottom:p,left:f,right:g,type:d===0&&p===0&&f===0&&g===0?"VALID":"EXPLICIT"},c=ba((e-o+d+p)/s+1,i),h=ba((t-a+f+g)/r+1,i)}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:u,outHeight:c,outWidth:h}}function tC(n,e,t,s,r,o,a,i,l,u,c){let h,d,p,f;if(n==="valid"&&(n=0),typeof n=="number"){h={top:n,bottom:n,left:n,right:n,front:n,back:n,type:n===0?"VALID":"NUMBER"};const m=QN([e,t,s,1],[i,l,u],1,[r,o,a],n,c);d=m[0],p=m[1],f=m[2]}else if(n==="same"){d=Math.ceil(e/r),p=Math.ceil(t/o),f=Math.ceil(s/a);const g=(d-1)*r+i-e,m=(p-1)*o+l-t,y=(f-1)*a+u-s,b=Math.floor(g/2),w=g-b,x=Math.floor(m/2),$=m-x,C=Math.floor(y/2),E=y-C;h={top:x,bottom:$,left:C,right:E,front:b,back:w,type:"SAME"}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:h,outDepth:d,outHeight:p,outWidth:f}}function ba(n,e){if(!e)return Math.trunc(n);switch(e){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${e}`)}}function er(n){const[e,t,s]=ya(n);return e===1&&t===1&&s===1}function Dt(n,e){return er(n)||er(e)}function Fr(n){return ya(n).every(e=>e>0)}function Ds(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function Gt(n,e,t){if(t!=null){if(typeof e=="string")throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);if(typeof e=="number")I(Rr(e),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);else if(typeof e=="object")e.forEach(s=>{s.forEach(r=>{I(Rr(r),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${r}.`)})});else throw Error(`Error in ${n}: Unknown padding parameter: ${e}`)}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nC(n,e){const s={x:N(n,"x","reshape","string_or_numeric")},r={shape:e};return R.runKernel(ec,s,r)}const F=D({reshape_:nC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sC(n,e,t,s,r){const o=N(n,"x","avgPool","float32"),a=1;I(Dt(t,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`);let i=o,l=!1;o.rank===3&&(l=!0,i=F(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),Gt("avgPool",s,r);const u={x:i},c={filterSize:e,strides:t,pad:s,dimRoundingMode:r};let h=R.runKernel(mu,u,c);return h=ee(h,o.dtype),l?F(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const mc=D({avgPool_:sC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rC(n,e,t,s,r,o="NDHWC"){const a=N(n,"x","avgPool3d","float32");let i=a,l=!1;a.rank===4&&(l=!0,i=F(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),I(o==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),I(typeof t=="number"&&t>0||Array.isArray(t)&&t[0]>0&&t[1]>0&&t[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${t}'`),Gt("avgPool3d",s,r);const u={x:i},c={filterSize:e,strides:t,pad:s,dimRoundingMode:r,dataFormat:o};let h=R.runKernel(gu,u,c);return h=ee(h,i.dtype),l?F(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const rw=D({avgPool3d_:rC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oC(n,e=0){I(n.length>=1,()=>"Pass at least one tensor to concat");const t=ga(n,"tensors","concat","string_or_numeric");if(t[0].dtype==="complex64"&&t.forEach(o=>{if(o.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype ${o.dtype}. `)}),t.length===1)return vs(t[0]);const s=t,r={axis:e};return R.runKernel(vu,s,r)}const at=D({concat_:oC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aC(n,e,t=!1,s=!1){let r=N(n,"a","matMul"),o=N(e,"b","matMul");[r,o]=Ze(r,o);const a={a:r,b:o},i={transposeA:t,transposeB:s};return R.runKernel(yu,a,i)}const Ne=D({matMul_:aC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iC(n){const t={x:N(n,"x","sigmoid","float32")};return R.runKernel(xi,t)}const ss=D({sigmoid_:iC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lC(n,e,t){const s=N(n,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");const r={x:s},o={begin:e,size:t};return R.runKernel(oc,r,o)}const Te=D({slice_:lC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uC(n){const t={x:N(n,"x","tanh","float32")};return R.runKernel(Ni,t)}const Lr=D({tanh_:uC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cC(n,e,t,s,r,o){const a=N(n,"forgetBias","basicLSTMCell"),i=N(e,"lstmKernel","basicLSTMCell"),l=N(t,"lstmBias","basicLSTMCell"),u=N(s,"data","basicLSTMCell"),c=N(r,"c","basicLSTMCell"),h=N(o,"h","basicLSTMCell"),d=at([u,h],1),p=Ne(d,i),f=Y(p,l),g=f.shape[0],m=f.shape[1]/4,y=[g,m],b=Te(f,[0,0],y),w=Te(f,[0,m],y),x=Te(f,[0,m*2],y),$=Te(f,[0,m*3],y),C=Y(O(ss(b),Lr(w)),O(c,ss(Y(a,x)))),E=O(Lr(C),ss($));return[C,E]}const hC=D({basicLSTMCell_:cC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dC(n,e,t){const s=N(n,"x","batchToSpaceND"),r=e.reduce((i,l)=>i*l);I(s.rank>=1+e.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${e.length}`),I(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),I(s.shape[0]%r===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${r}`);const o={x:s},a={blockShape:e,crops:t};return R.runKernel(bu,o,a)}const gc=D({batchToSpaceND_:dC});function pC(n){let e;return n.rank===0||n.rank===1?e=F(n,[1,1,1,n.size]):n.rank===2?e=F(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?e=F(n,[1,n.shape[0],n.shape[1],n.shape[2]]):e=n,e}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fC(n,e,t,s,r,o){o==null&&(o=.001);const a=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let u;r!=null&&(u=N(r,"scale","batchNorm"));let c;s!=null&&(c=N(s,"offset","batchNorm")),I(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),I(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),I(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const d={x:pC(a),scale:u,offset:c,mean:i,variance:l},p={varianceEpsilon:o},f=R.runKernel(Au,d,p);return F(f,a.shape)}const Ri=D({batchNorm_:fC});function mC(n,e,t,s,r,o){const a=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let u;r!=null&&(u=N(r,"scale","batchNorm"));let c;return s!=null&&(c=N(s,"offset","batchNorm")),I(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),I(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),I(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&I(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&I(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Ri(a,i,l,c,u,o)}const ow=D({batchNorm2d_:mC});function gC(n,e,t,s,r,o){const a=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let u;r!=null&&(u=N(r,"scale","batchNorm"));let c;return s!=null&&(c=N(s,"offset","batchNorm")),I(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),I(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),I(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&I(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&I(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Ri(a,i,l,c,u,o)}const aw=D({batchNorm3d_:gC});function yC(n,e,t,s,r,o){const a=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let u;r!=null&&(u=N(r,"scale","batchNorm"));let c;return s!=null&&(c=N(s,"offset","batchNorm")),I(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),I(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),I(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&I(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&I(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Ri(a,i,l,c,u,o)}const iw=D({batchNorm4d_:yC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bC(n,e,t){const s=N(n,"x","bincount"),r=N(e,"weights","bincount");I(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),I(t>=0,()=>`size must be non-negative, but got ${t}.`),I(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);const o={x:s,weights:r},a={size:t};return R.runKernel(Kd,o,a)}const lw=D({bincount_:bC});/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xC(n,e){const t=N(n,"x","bitwiseAnd"),s=N(e,"y","bitwiseAnd");if(!Ce(t.shape,s.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${t.shape}, y: ${s.shape}`);if(t.dtype!=="int32"||s.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${t.dtype} and type of y: ${s.dtype}`);const r={a:t,b:s};return R.runKernel(xu,r)}const wC=D({bitwiseAnd_:xC});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vC(n,e){const t=N(n,"s0","broadcastArgs","int32"),s=N(e,"s1","broadcastArgs","int32");if(t.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${t.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);const r={s0:t,s1:s};return R.runKernel(Xd,r)}const $C=D({broadcastArgs_:vC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SC(n,e){let t=N(n,"broadcastTo","x");const s=t.shape;if(hn(e),e.lengtht.rank){const u=t.shape.slice();for(;u.length=0;u--)if(r[u]===e[u])o[u]=1;else if(t.shape[u]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${e}].`);if(o.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return vs(t);const i={x:t},l={reps:o};return R.runKernel(Ci,i,l)}const yo=D({broadcastTo_:SC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IC(n){const t={x:N(n,"x","ceil","float32")};return R.runKernel(Va,t)}const uw=D({ceil_:IC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Do(n,e,t){hn(n),t=t||Kr(e);const s={shape:n,value:e,dtype:t};return R.runKernel(hp,{},s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NC(n,e,t){const s=N(n,"x","clipByValue");if(I(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`),e===t)return Do(s.shape,e,s.dtype);const r={x:s},o={clipValueMin:e,clipValueMax:t};return R.runKernel(Wa,r,o)}const ln=D({clipByValue_:NC});function CC(n){return at(n,0)}const cw=D({concat1d_:CC});function kC(n,e){return at(n,e)}const hw=D({concat2d_:kC});function TC(n,e){return at(n,e)}const dw=D({concat3d_:TC});function EC(n,e){return at(n,e)}const pw=D({concat4d_:EC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AC(n,e,t,s,r="NHWC",o=[1,1],a){const i=N(n,"x","conv2d","float32"),l=N(e,"filter","conv2d","float32");let u=i,c=!1;i.rank===3&&(c=!0,u=F(i,[1,i.shape[0],i.shape[1],i.shape[2]])),I(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),I(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Gt("conv2d",s,a);const h=r==="NHWC"?u.shape[3]:u.shape[1];I(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),I(Dt(t,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`),I(Fr(o),()=>"Error in conv2D: Dilated rates should be larger than 0."),I(Fr(t),()=>"Error in conv2D: Strides should be larger than 0.");const d={x:u,filter:l},p={strides:t,pad:s,dataFormat:r,dilations:o,dimRoundingMode:a},f=R.runKernel($u,d,p);return c?F(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const tr=D({conv2d_:AC});function RC(n,e,t,s,r="NWC",o=1,a){const i=N(n,"x","conv1d"),l=N(e,"filter","conv1d");let u=i,c=!1;i.rank===2&&(c=!0,u=F(i,[1,i.shape[0],i.shape[1]])),I(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),I(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Gt("conv1d",s,a),I(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),I(Dt(t,o),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${o}'`),I(Fr(o),()=>"Error in conv1D: Dilated rates should be larger than 0."),I(Fr(t),()=>"Error in conv1D: Stride should be larger than 0."),I(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);const h=F(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=F(u,[u.shape[0],1,u.shape[1],u.shape[2]]),m=tr(d,h,[1,t],s,"NHWC",[1,o],a);return c?F(m,[m.shape[2],m.shape[3]]):F(m,[m.shape[0],m.shape[2],m.shape[3]])}const lf=D({conv1d_:RC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DC(n,e,t,s,r,o="NHWC",a){I(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let i=n,l=e,u=!1;e.rank===3&&(u=!0,l=F(e,[1,e.shape[0],e.shape[1],e.shape[2]]),i=[1,n[0],n[1],n[2]]),I(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),I(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),I(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);const c=o==="NHWC"?i[3]:i[1],h=o==="NHWC"?l.shape[3]:l.shape[1];I(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),I(h===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${t.shape[3]}.`),Gt("conv2dDerInput",r,a);const d={dy:l,filter:t},p={strides:s,pad:r,dataFormat:o,dimRoundingMode:a,inputShape:i},f=R.runKernel(Su,d,p);return u?F(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const uf=D({conv2DBackpropInput_:DC});function OC(n,e,t,s,r,o){const a=N(n,"x","conv2dTranspose"),i=N(e,"filter","conv2dTranspose");return uf(t,a,i,s,r,"NHWC",o)}const cf=D({conv2dTranspose_:OC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _C(n,e,t,s,r="NDHWC",o=[1,1,1]){const a=N(n,"x","conv3d"),i=N(e,"filter","conv3d");let l=a,u=!1;a.rank===4&&(u=!0,l=F(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),I(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),I(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),I(Dt(t,o),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`),I(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`),I(Fr(o),()=>"Error in conv3D: Dilated rates should be larger than 0."),I(Fr(t),()=>"Error in conv3D: Strides should be larger than 0.");const c={x:l,filter:i},h={strides:t,pad:s,dataFormat:r,dilations:o},d=R.runKernel(Iu,c,h);return u?F(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const fw=D({conv3d_:_C});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FC(n,e,t,s,r){I(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let o=n,a=e,i=!1;e.rank===4&&(i=!0,a=F(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),o=[1,n[0],n[1],n[2],n[3]]);const l=o[4],u=a.shape[4];I(o.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`),I(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),I(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),I(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),I(u===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);const c={dy:a,filter:t},h={pad:r,strides:s,inputShape:o},d=R.runKernel(Qd,c,h);return i?F(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const mw=D({conv3DBackpropInput_:FC});function LC(n,e,t,s,r){const o=N(n,"x","conv3dTranspose"),a=N(e,"filter","conv3dTranspose");return mw(t,o,a,s,r)}const gw=D({conv3dTranspose_:LC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PC(n){const t={x:N(n,"x","cos","float32")};return R.runKernel(Ua,t)}const yc=D({cos_:PC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zC(n){const t={x:N(n,"x","cosh","float32")};return R.runKernel(Ga,t)}const hf=D({cosh_:zC});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MC(n,e=0,t=!1,s=!1){const o={x:N(n,"x","cumprod")},a={axis:e,exclusive:t,reverse:s};return R.runKernel(ep,o,a)}const Vl=D({cumprod_:MC});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BC(n,e=0,t=!1,s=!1){const o={x:N(n,"x","cumsum")},a={axis:e,exclusive:t,reverse:s};return R.runKernel(Nu,o,a)}const df=D({cumsum_:BC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VC(n,e,t,s=!1){const r=N(n,"x","denseBincount"),o=N(e,"weights","denseBincount");I(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),I(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),I(t>=0,()=>`size must be non-negative, but got ${t}.`),I(o.size===r.size||o.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${o.shape}.`);const a={x:r,weights:o},i={size:t,binaryOutput:s};return R.runKernel(np,a,i)}const nd=D({denseBincount_:VC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WC(n,e,t="NHWC"){const s=N(n,"x","depthToSpace","float32"),r=t==="NHWC"?s.shape[1]:s.shape[2],o=t==="NHWC"?s.shape[2]:s.shape[3],a=t==="NHWC"?s.shape[3]:s.shape[1];I(e>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${e}`),I(r*e>=0,()=>`Negative dimension size caused by overflow when multiplying + ${r} and ${e} for depthToSpace with input shape + ${s.shape}`),I(o*e>=0,()=>`Negative dimension size caused by overflow when multiplying + ${o} and ${e} for depthToSpace with input shape + ${s.shape}`),I(a%(e*e)===0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${a} for depthToSpace with input shape ${s.shape}`);const i={x:s},l={blockSize:e,dataFormat:t};return R.runKernel(sp,i,l)}const yw=D({depthToSpace_:WC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UC(n,e,t,s,r="NHWC",o=[1,1],a){const i=N(n,"x","depthwiseConv2d","float32"),l=N(e,"filter","depthwiseConv2d","float32");let u=i,c=!1;i.rank===3&&(c=!0,u=F(i,[1,i.shape[0],i.shape[1],i.shape[2]])),I(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),I(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const h=r==="NHWC"?u.shape[3]:u.shape[1];I(h===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`),Gt("depthwiseConv2d",s,a);const d={x:u,filter:l},p={strides:t,pad:s,dataFormat:r,dilations:o,dimRoundingMode:a},f=R.runKernel(Cu,d,p);return c?F(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const Di=D({depthwiseConv2d_:UC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GC(n){const t={x:N(n,"x","diag")};return R.runKernel(ap,t)}const HC=D({diag_:GC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jC(n,e,t,s,r=[1,1],o="NHWC"){const a=N(n,"x","dilation2d"),i=N(e,"filter","dilation2d");I(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),I(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),I(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let l=a,u=!1;a.rank===3&&(l=F(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0),I(l.shape[3]===i.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${i.shape[2]}`);const c={x:l,filter:i},h={strides:t,pad:s,dilations:r},d=R.runKernel(ku,c,h);return u?F(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const bw=D({dilation2d_:jC});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pr(n,e){const t=n.length,s=[];for(let r=0;r1&&a===1&&s.unshift(o)}return s}function it(n,e){const t=[];for(let s=0;s1)&&t.unshift(o)}return t}function ye(n,e){const t=Math.max(n.length,e.length),s=new Array(t);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${s.rank}.`);const r=t.rank===1?t.size:t.shape[1],o=s.rank===1?s.size:s.shape[0];if(I(r===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${o}.`),t.rank===1&&s.rank===1){const a=F(t,[1,-1]),i=F(s,[-1,1]),l=Ne(a,i);return F(l,[])}else if(t.rank===1&&s.rank===2){const a=F(t,[1,-1]),i=F(s,[s.shape[0],s.shape[1]]),l=Ne(a,i);return F(l,[l.size])}else if(t.rank===2&&s.rank===1){const a=F(s,[-1,1]),i=Ne(t,a);return F(i,[i.size])}else{const a=F(s,[s.shape[0],s.shape[1]]);return Ne(t,a)}}const ww=D({dot_:ZC});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JC(n,...e){const t=e.map((r,o)=>N(r,`tensors${o}`,"einsum")),s={equation:n};return R.runKernel(lp,t,s)}const po=D({einsum_:JC});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QC(n){const t={x:N(n,"x","elu","float32")};return R.runKernel(ja,t)}const Oi=D({elu_:QC});/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ek(n,e){const t=N(n,"x","ensureShape","string_or_numeric");if(!cx(t.shape,e))throw new Error(`EnsureShape: Shape of tensor ${t.shape} is not compatible with expected shape ${e}`);return n}const tk=D({ensureShape_:ek});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nk(n){let e=N(n,"x","erf");I(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=ee(e,"float32"));const t={x:e};return R.runKernel(qa,t)}const pf=D({erf_:nk});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ff(n,e){for(let t=0;tn[o]);return[t,r]}function nt(n,e){const t=e.map(s=>1);return vw(n,t,e)}function Ot(n,e,t){I(ff(e,t),()=>`${n} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function Je(n,e){if(ff(n,e))return null;const t=[];for(let s=0;st.push(s)),t}function cr(n){return n.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function st(n,e){const t=[];for(let s=e-n;s"Axis must be <= rank of the tensor");const s={input:t},r={dim:e};return R.runKernel(Eu,s,r)}const Lt=D({expandDims_:dk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pk(n){const t={x:N(n,"x","expm1")};return R.runKernel(Xa,t)}const Iw=D({expm1_:pk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fk(n,e){const t=N(n,"x","tile","string_or_numeric");I(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);const s={x:t},r={reps:e};return R.runKernel(Ci,s,r)}const kn=D({tile_:fk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mk(n,e,t,s="float32"){e==null&&(e=n);const r=ve([n,e],s),o=n<=e?n:e;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got + rank ${o.rank}.`),I(Rr(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let a=o,i=!1;o.rank===3&&(i=!0,a=F(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const l={x:a},u={depthRadius:e,bias:t,alpha:s,beta:r},c=R.runKernel(Mu,l,u);return i?F(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Tw=D({localResponseNormalization_:Tk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ek(n){const t={x:N(n,"x","log","float32")};return R.runKernel(si,t)}const vn=D({log_:Ek});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ak(n){const t={x:N(n,"x","log1p")};return R.runKernel(ri,t)}const wc=D({log1p_:Ak});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function CJ(n){return I(Zs(n),()=>"The f passed in grad(f) must be a function"),(e,t)=>{const s=N(e,"x","tf.grad","string_or_numeric"),r=t!=null?N(t,"dy","tf.grad"):null;return R.tidy(()=>{const{value:o,grads:a}=R.gradients(()=>n(s),[s],r);return r!=null&&Rt(o.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),vc(a),a[0]})}}function kJ(n){return I(Zs(n),()=>"The f passed in grads(f) must be a function"),(e,t)=>{I(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=ga(e,"args","tf.grads","string_or_numeric"),r=t!=null?N(t,"dy","tf.grads"):null;return R.tidy(()=>{const{value:o,grads:a}=R.gradients(()=>n(...s),s,r);return r!=null&&Rt(o.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),vc(a),a})}}function TJ(n){return I(Zs(n),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{I(e instanceof Re,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),I(t==null||t instanceof Re,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:r}=R.gradients(()=>n(e),[e],t);return vc(s),{grad:s[0],value:r}}}function EJ(n){return I(Zs(n),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{I(Array.isArray(e)&&e.every(r=>r instanceof Re),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),I(t==null||t instanceof Re,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=R.gradients(()=>n(...e),e,t);return t!=null&&Rt(s.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),vc(s.grads),s}}function Rk(n,e){I(Zs(n),()=>"The f passed in variableGrads(f) must be a function"),I(e==null||Array.isArray(e)&&e.every(u=>u instanceof zl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const t=e!=null;if(!t){e=[];for(const u in R.registeredVariables)e.push(R.registeredVariables[u])}const s=t?e.filter(u=>!u.trainable):null,r=e.length;e=e.filter(u=>u.trainable),I(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);const o=!0,{value:a,grads:i}=R.gradients(n,e,null,o);I(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),I(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const l={};return e.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),s!=null&&s.forEach(u=>l[u.name]=null),{value:a,grads:l}}function Cs(n){return R.customGrad(n)}function vc(n){if(n.filter(t=>t==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that + the f you passed encloses all operations that lead from x to y.`)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dk(n){const t={x:N(n,"x","neg")};return R.runKernel(ju,t)}const Ge=D({neg_:Dk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ok(n){const t={x:N(n,"x","softplus")};return R.runKernel(wi,t)}const Oo=D({softplus_:Ok});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _k(n){const e=N(n,"x","logSigmoid");return Cs(s=>({value:Ge(Oo(Ge(s))),gradFunc:a=>O(a,ss(Ge(s)))}))(e)}const Ew=D({logSigmoid_:_k});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fk(n,e){let t=N(n,"a","sub"),s=N(e,"b","sub");[t,s]=Ze(t,s);const r={a:t,b:s};return R.runKernel(Si,r)}const ae=D({sub_:Fk});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lk(n,e=-1){const t=N(n,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return Cs((r,o)=>{const i=En(r,e,!0),l=ae(r,i),u=ae(ee(l,"float32"),vn(ie(un(l),e,!0)));return o([u]),{value:u,gradFunc:(h,d)=>{const[p]=d,f=!0,g=un(p);return ae(h,O(ie(h,e,f),g))}}})(t)}const gf=D({logSoftmax_:Lk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pk(n,e=null,t=!1){const s=N(n,"x","logSumExp"),r=Se(e,s.shape),o=En(s,r,!0),a=ae(s,o),i=un(a),l=ie(i,r),u=vn(l),c=Y(F(o,u.shape),u);if(t){const h=nt(c.shape,r);return F(c,h)}return c}const $c=D({logSumExp_:Pk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zk(n,e){const t=N(n,"a","logicalAnd","bool"),s=N(e,"b","logicalAnd","bool");ye(t.shape,s.shape);const r={a:t,b:s};return R.runKernel(Lu,r)}const Gn=D({logicalAnd_:zk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mk(n){const t={x:N(n,"x","logicalNot","bool")};return R.runKernel(Pu,t)}const Sc=D({logicalNot_:Mk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bk(n,e){const t=N(n,"a","logicalOr","bool"),s=N(e,"b","logicalOr","bool");ye(t.shape,s.shape);const r={a:t,b:s};return R.runKernel(zu,r)}const yf=D({logicalOr_:Bk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vk(n,e){const t=N(n,"a","logicalXor","bool"),s=N(e,"b","logicalXor","bool");return ye(t.shape,s.shape),Gn(yf(n,e),Sc(Gn(n,e)))}const Aw=D({logicalXor_:Vk});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nl=2147483648;function Wk(n,e,t="left"){const s=N(n,"sortedSequence","searchSorted"),r=N(e,"values","searchSorted"),o=s.shape[s.shape.length-1],a=r.shape[r.shape.length-1],i=F(s,[-1,o]),l=F(r,[-1,a]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(G(l.shape)>=nl)throw new Error(`values tensor size must less than ${nl}`);if(i.shape[1]>=nl)throw new Error(`trailing dim_size must less than ${nl} for int32 output type, was ${i.shape[1]}`);const u={sortedSequence:i,values:l},c={side:t};return R.runKernel(_p,u,c)}const bf=D({searchSorted_:Wk});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Uk(n,e){return bf(n,e,"left")}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gk(n,e,t,s,r){const o=N(n,"x","maxPool"),a=1;let i=o,l=!1;o.rank===3&&(l=!0,i=F(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),I(Dt(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),Gt("maxPool",s,r);const u={x:i},c={filterSize:e,strides:t,pad:s,dimRoundingMode:r},h=R.runKernel(Vu,u,c);return l?F(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Ic=D({maxPool_:Gk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hk(n,e=[1,1,1],t,s,r,o="NDHWC"){const a=N(n,"x","maxPool3d");let i=a,l=!1;a.rank===4&&(l=!0,i=F(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),I(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),Gt("maxPool3d",s,r);const u={x:i},c={filterSize:e,strides:t,pad:s,dimRoundingMode:r,dataFormat:o},h=R.runKernel(Wu,u,c);return l?F(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const Rw=D({maxPool3d_:Hk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jk(n,e,t,s,r=!1){const a={x:N(n,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:s,includeBatchInIndex:r},l=R.runKernel(wp,a,i);return{result:l[0],indexes:l[1]}}const qk=D({maxPoolWithArgmax_:jk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kk(n,e){let t=N(n,"a","maximum"),s=N(e,"b","maximum");[t,s]=Ze(t,s),t.dtype==="bool"&&(t=ee(t,"int32"),s=ee(s,"int32")),ye(t.shape,s.shape);const r={a:t,b:s};return R.runKernel(oi,r)}const Os=D({maximum_:Kk});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xk(n,e=null,t=!1){const r={x:N(n,"x","mean")},o={axis:e,keepDims:t};return R.runKernel(Uu,r,o)}const et=D({mean_:Xk});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ct(n,e="float32"){if(hn(n),e==="complex64"){const s=ct(n,"float32"),r=ct(n,"float32");return Js(s,r)}const t=Et(G(n),e);return R.makeTensor(t,n,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rn(n,e="float32"){if(hn(n),e==="complex64"){const s=rn(n,"float32"),r=ct(n,"float32");return Js(s,r)}const t=cu(G(n),e);return R.makeTensor(t,n,e)}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yk(n,e,{indexing:t="xy"}={}){if(t!=="xy"&&t!=="ij")throw new TypeError(`${t} is not a valid third argument to meshgrid`);if(n===void 0)return[];let s=N(n,"x","meshgrid",n instanceof Re?n.dtype:"float32");if(e===void 0)return[s];let r=N(e,"y","meshgrid",e instanceof Re?e.dtype:"float32");const o=G(s.shape),a=G(r.shape);return t==="xy"?(s=F(s,[1,-1]),r=F(r,[-1,1]),[Ne(rn([a,1],s.dtype),s),Ne(r,rn([1,o],r.dtype))]):(s=F(s,[-1,1]),r=F(r,[1,-1]),[Ne(s,rn([1,a],s.dtype)),Ne(rn([o,1],r.dtype),r)])}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zk(n,e){let t=N(n,"a","minimum"),s=N(e,"b","minimum");[t,s]=Ze(t,s),t.dtype==="bool"&&(t=ee(t,"int32"),s=ee(s,"int32")),ye(t.shape,s.shape);const r={a:t,b:s};return R.runKernel(ai,r)}const zr=D({minimum_:Zk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jk(n,e,t){I(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);const s=N(n,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");I(e.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${e.length}.`);const r=t==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),I(e[i][0]>=0&&e[i][0]<=s.shape[i]-r&&e[i][1]>=0&&e[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);const o={paddings:e,mode:t},a={x:s};return R.runKernel(Hu,a,o)}const Dw=D({mirrorPad_:Jk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qk(n,e){let t=N(n,"a","mod"),s=N(e,"b","mod");[t,s]=Ze(t,s);const r={a:t,b:s};return R.runKernel(ii,r)}const Ow=D({mod_:Qk});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eT(n,e=null,t=!1){n=N(n,"x","moments");const s=Se(e,n.shape),r=et(n,s,t);let o=r.shape;t||(o=nt(r.shape,s));const a=ze(ae(ee(n,"float32"),F(r,o))),i=et(a,s,t);return{mean:r,variance:i}}const Nc=D({moments_:eT});function tT(n,e,t,s){const r=N(e,"data","multiRNNCell"),o=ga(t,"c","multiRNNCell"),a=ga(s,"h","multiRNNCell");let i=r;const l=[];for(let h=0;h2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);t=t||Math.random();const l={logits:a===1?F(r,[1,-1]):r},u={numSamples:e,seed:t,normalized:s},c=R.runKernel(vp,l,u);return a===1?F(c,[c.size]):c}const rT=D({multinomial_:sT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oT(n,e){let t=N(n,"a","notEqual","string_or_numeric"),s=N(e,"b","notEqual","string_or_numeric");[t,s]=Ze(t,s),ye(t.shape,s.shape);const r={a:t,b:s};return R.runKernel(qu,r)}const $o=D({notEqual_:oT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aT(n,e,t=1,s=0,r="int32"){if(e<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);const a={indices:N(n,"indices","oneHot","int32")},i={dtype:r,depth:e,onValue:t,offValue:s};return R.runKernel(Xu,a,i)}const va=D({oneHot_:aT});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iT(n){const t={x:N(n,"x","onesLike")};return R.runKernel(Ku,t)}const $n=D({onesLike_:iT});function lT(n,e){const t=N(n,"v1","outerProduct"),s=N(e,"v2","outerProduct");I(t.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${s.rank}.`);const r=F(t,[-1,1]),o=F(s,[1,-1]);return Ne(r,o)}const uT=D({outerProduct_:lT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cT(n,e,t=0){const s=N(n,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const r={paddings:e,constantValue:t},o={x:s};return R.runKernel(Zu,o,r)}const dr=D({pad_:cT});function hT(n,e,t=0){return I(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),dr(n,[e],t)}const dT=D({pad1d_:hT});function pT(n,e,t=0){return I(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),dr(n,e,t)}const fT=D({pad2d_:pT});function mT(n,e,t=0){return I(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),dr(n,e,t)}const gT=D({pad3d_:mT});function yT(n,e,t=0){return I(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),dr(n,e,t)}const bT=D({pad4d_:yT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xT(n,e,t){const s=N(n,"x","spaceToBatchND");I(s.rank>=1+e.length,()=>`input rank ${s.rank} should be > than [blockShape] ${e.length}`),I(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),I(s.shape.reduce((a,i,l)=>l>0&&l<=e.length?a&&(i+t[l-1][0]+t[l-1][1])%e[l-1]===0:a,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);const r={x:s},o={blockShape:e,paddings:t};return R.runKernel(ic,r,o)}const Cc=D({spaceToBatchND_:xT});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wT(n,e,t,s,r,o,a){r==null&&(r=[1,1]),o==null&&(o=1),s===0&&(s="valid");const i=N(n,"x","maxPool");let l=i,u=!1;i.rank===3&&(u=!0,l=F(i,[1,i.shape[0],i.shape[1],i.shape[2]])),I(Dt(o,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${r}'`);const c=Dn(l.shape,e,o,r,s),h=[c.dilationHeight,c.dilationWidth];let d;s==="same"?d=$T([c.filterHeight,c.filterWidth],h):d=[[0,0],[0,0]];const p=h[0]===1&&h[1]===1,[f,g]=vT([c.inHeight,c.inWidth],h,d),m=p?s:"valid",y=p?l:Cc(l,h,f),w=(t==="avg"?()=>mc(y,e,o,m,a):()=>Ic(y,e,o,m,a))(),x=p?w:gc(w,h,g);return u?F(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function vT(n,e,t){const s=t.map(c=>c[0]),r=t.map(c=>c[1]),o=n.concat(s,r),a=e.map((c,h)=>(c-o[h]%c)%c),i=r.map((c,h)=>c+a[h]),l=e.map((c,h)=>[s[h],i[h]]),u=e.map((c,h)=>[0,a[h]]);return[l,u]}function $T(n,e){const s=n.map((a,i)=>a+(a-1)*(e[i]-1)).map(a=>a-1),r=s.map(a=>Math.floor(a/2)),o=s.map((a,i)=>a-r[i]);return s.map((a,i)=>[r[i],o[i]])}const _w=D({pool_:wT});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ST(n,e){const t=N(n,"x","prelu"),s=N(e,"alpha","prelu"),r={x:t,alpha:s};return R.runKernel(Ju,r)}const kc=D({prelu_:ST});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IT(n,e=null,t=!1){let s=N(n,"x","prod");s.dtype==="bool"&&(s=ee(s,"int32"));const r={x:s},o={axis:e,keepDims:t};return R.runKernel(Qu,r,o)}const Fw=D({prod_:IT});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NT(n,e,t,s){const r=n.map((c,h)=>N(c,`tensors${h}`,"raggedGather","int32")),o=N(e,"paramsDenseValues","raggedGather"),a=N(t,"indices","raggedGather","int32"),i={paramsNestedSplits:r,paramsDenseValues:o,indices:a},l={outputRaggedRank:s},u=R.runKernel(Np,i,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}const CT=D({raggedGather_:NT});/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kT(n,e,t){const s=N(n,"starts","raggedRange"),r=N(e,"limits","raggedRange",s.dtype),o=N(t,"deltas","raggedRange",s.dtype),a={starts:s,limits:r,deltas:o},i=R.runKernel(Cp,a);return{rtNestedSplits:i[0],rtDenseValues:i[1]}}const TT=D({raggedRange_:kT});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ET(n,e,t,s,r){const o=N(n,"shape","raggedTensorToTensor","int32"),a=N(e,"values","raggedTensorToTensor"),i=N(t,"defaultValue","raggedTensorToTensor",a.dtype),l=s.map((h,d)=>N(h,`tensors${d}`,"raggedTensorToTensor","int32")),u={shape:o,values:a,defaultValue:i,rowPartitionTensors:l},c={rowPartitionTypes:r};return R.runKernel(kp,u,c)}const AT=D({raggedTensorToTensor_:ET});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RT(n,e,t){hn(n);const s=G(n);let r=null;if(t==null||t==="float32")r=new Float32Array(s);else if(t==="int32")r=new Int32Array(s);else if(t==="bool")r=new Uint8Array(s);else throw new Error(`Unknown data type ${t}`);for(let o=0;o>>0,d-=l,d*=l,l=d>>>0,d-=l,l+=d*4294967296}return(l>>>0)*23283064365386963e-26};return u}t&&t.exports?t.exports=a:this.alea=a})(OT,n)})(bl)),bl.exports}var xl={exports:{}},FT=xl.exports,Ay;function LT(){return Ay||(Ay=1,(function(n){(function(e,t,s){function r(i){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},i===(i|0)?l.x=i:u+=i;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&o(c,u),h.state=function(){return o(u,{})}),h}t&&t.exports?t.exports=a:this.xor128=a})(FT,n)})(xl)),xl.exports}var wl={exports:{}},PT=wl.exports,Ry;function zT(){return Ry||(Ry=1,(function(n){(function(e,t,s){function r(i){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,i===(i|0)?l.x=i:u+=i;for(var c=0;c>>4),l.next()}function o(i,l){return l.x=i.x,l.y=i.y,l.z=i.z,l.w=i.w,l.v=i.v,l.d=i.d,l}function a(i,l){var u=new r(i),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&o(c,u),h.state=function(){return o(u,{})}),h}t&&t.exports?t.exports=a:this.xorwow=a})(PT,n)})(wl)),wl.exports}var vl={exports:{}},MT=vl.exports,Dy;function BT(){return Dy||(Dy=1,(function(n){(function(e,t,s){function r(i){var l=this;l.next=function(){var c=l.x,h=l.i,d,p;return d=c[h],d^=d>>>7,p=d^d<<24,d=c[h+1&7],p^=d^d>>>10,d=c[h+3&7],p^=d^d>>>3,d=c[h+4&7],p^=d^d<<7,d=c[h+7&7],d=d^d<<13,p^=d^d<<9,c[h]=p,l.i=h+1&7,p};function u(c,h){var d,p=[];if(h===(h|0))p[0]=h;else for(h=""+h,d=0;d0;--d)c.next()}u(l,i)}function o(i,l){return l.x=i.x.slice(),l.i=i.i,l}function a(i,l){i==null&&(i=+new Date);var u=new r(i),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.x&&o(c,u),h.state=function(){return o(u,{})}),h}t&&t.exports?t.exports=a:this.xorshift7=a})(MT,n)})(vl)),vl.exports}var $l={exports:{}},VT=$l.exports,Oy;function WT(){return Oy||(Oy=1,(function(n){(function(e,t,s){function r(i){var l=this;l.next=function(){var c=l.w,h=l.X,d=l.i,p,f;return l.w=c=c+1640531527|0,f=h[d+34&127],p=h[d=d+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=h[d]=f^p,l.i=d,f+(c^c>>>16)|0};function u(c,h){var d,p,f,g,m,y=[],b=128;for(h===(h|0)?(p=h,h=null):(h=h+"\0",p=0,b=Math.max(b,h.length)),f=0,g=-32;g>>15,p^=p<<4,p^=p>>>13,g>=0&&(m=m+1640531527|0,d=y[g&127]^=p+m,f=d==0?f+1:0);for(f>=128&&(y[(h&&h.length||0)&127]=-1),f=127,g=512;g>0;--g)p=y[f+34&127],d=y[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,y[f]=p^d;c.w=m,c.X=y,c.i=f}u(l,i)}function o(i,l){return l.i=i.i,l.w=i.w,l.X=i.X.slice(),l}function a(i,l){i==null&&(i=+new Date);var u=new r(i),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.X&&o(c,u),h.state=function(){return o(u,{})}),h}t&&t.exports?t.exports=a:this.xor4096=a})(VT,n)})($l)),$l.exports}var Sl={exports:{}},UT=Sl.exports,_y;function GT(){return _y||(_y=1,(function(n){(function(e,t,s){function r(i){var l=this,u="";l.next=function(){var h=l.b,d=l.c,p=l.d,f=l.a;return h=h<<25^h>>>7^d,d=d-p|0,p=p<<24^p>>>8^f,f=f-h|0,l.b=h=h<<20^h>>>12^d,l.c=d=d-p|0,l.d=p<<16^d>>>16^f,l.a=f-h|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,i===Math.floor(i)?(l.a=i/4294967296|0,l.b=i|0):u+=i;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&o(c,u),h.state=function(){return o(u,{})}),h}t&&t.exports?t.exports=a:this.tychei=a})(UT,n)})(Sl)),Sl.exports}var Il={exports:{}};const HT={},jT=Object.freeze(Object.defineProperty({__proto__:null,default:HT},Symbol.toStringTag,{value:"Module"})),qT=AI(jT);var KT=Il.exports,Fy;function XT(){return Fy||(Fy=1,(function(n){(function(e,t,s){var r=256,o=6,a=52,i="random",l=s.pow(r,o),u=s.pow(2,a),c=u*2,h=r-1,d;function p(x,$,C){var E=[];$=$==!0?{entropy:!0}:$||{};var A=y(m($.entropy?[x,w(t)]:x??b(),3),E),k=new f(E),T=function(){for(var S=k.g(o),_=l,P=0;S=c;)S/=2,_/=2,P>>>=1;return(S+P)/_};return T.int32=function(){return k.g(4)|0},T.quick=function(){return k.g(4)/4294967296},T.double=T,y(w(k.S),t),($.pass||C||function(S,_,P,V){return V&&(V.S&&g(V,k),S.state=function(){return g(k,{})}),P?(s[i]=S,_):S})(T,A,"global"in $?$.global:this==s,$.state)}function f(x){var $,C=x.length,E=this,A=0,k=E.i=E.j=0,T=E.S=[];for(C||(x=[C++]);Awf(s,r,t))}function xf(){return R.backend.floatPrecision()===32?ZT:Lw}function sd(n,e,t){let s=!0;if((ut(n)||ut(e))&&(s=!1),ut(n)&&ut(e)&&(s=!0),s){const a=n.constructor.name,i=e.constructor.name;if(a!==i)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${i}`)}if(Array.isArray(n)&&Array.isArray(e)){const a=ls(n),i=ls(e);if(!Ce(a,i))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`)}const r=ut(n)?n:is(n),o=ut(e)?e:is(e);if(r.length!==o.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${o.length}. +Actual: ${r}. +Expected: ${o}.`);for(let a=0;ae.fail(),()=>e()),typeof expect<"u"&&expect().nothing()}function e2(n,e){const t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return es(n)||es(n[0])||es(e)||es(e[0])?sd(n,t,(s,r)=>s==r):sd(n,e,(s,r)=>wf(s,r,0))}function t2(n,e,t){if(t==null&&(t=xf()),!wf(n,e,t))throw new Error(`Numbers differ: actual === ${n}, expected === ${e}`);typeof expect<"u"&&expect().nothing()}function wf(n,e,t){return!isFinite(n)&&!isFinite(e)?!0:!(isNaN(n)||isNaN(e)||Math.abs(n-e)>t)}function n2(n,e,t){for(let s=0;st)throw new Error(`Value out of range:${n[s]} low: ${e}, high: ${t}`)}function s2(n,e){const t=new Float32Array(n),s=new Float32Array(e);if(t.length!==s.length)throw new Error(`Expected ArrayBuffer to be of length ${s.length}, but it was ${t.length}`);for(let r=0;r{e.addEventListener("loadeddata",s=>t(e)),e.load()})}async function o2(n){await n.play(),"requestVideoFrameCallback"in n&&await new Promise(e=>{n.requestVideoFrameCallback(e)})}const AJ=Object.freeze(Object.defineProperty({__proto__:null,TEST_EPSILON_FLOAT16:Lw,createVideoElement:r2,encodeStrings:Pw,expectArrayBuffersEqual:s2,expectArraysClose:JT,expectArraysEqual:e2,expectNumbersClose:t2,expectPromiseToFail:QT,expectValuesInRange:n2,play:o2,testEpsilon:xf},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vf{constructor(e,t,s,r,o){this.mean=e,this.stdDev=t,this.dtype=s,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const a=o||Math.random();this.random=_o.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){const r=this.nextVal;return this.nextVal=NaN,r}let e,t,s=!1;for(;!s;){let r,o,a;do r=2*this.random()-1,o=2*this.random()-1,a=r*r+o*o;while(a>=1||a===0);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*i,t=this.mean+this.stdDev*o*i,(!this.truncated||this.isValidTruncated(e))&&(s=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class a2{constructor(e,t,s,r){this.alpha=e,this.beta=1/t,this.dtype=s;const o=r||Math.random();this.randu=_o.alea(o.toString()),this.randn=new vf(0,1,s,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,s,r,o,a;for(;;){do r=this.randn.nextValue(),a=1+this.c*r;while(a<=0);if(a*=a*a,e=r*r,t=1-.331*e*e,s=.5*e+this.d*(1-a+Math.log(a)),o=this.randu(),othis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=s,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=_o.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function l2(n,e,t=1,s="float32",r){if(hn(n),t==null&&(t=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);const o=new a2(e,t,s,r),a=ve(n,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),An(e,0)}const $2=D({reverse1d_:v2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function S2(n,e){const t=N(n,"x","reverse");return I(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),An(t,e)}const I2=D({reverse2d_:S2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N2(n,e){const t=N(n,"x","reverse");return I(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),An(t,e)}const C2=D({reverse3d_:N2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function k2(n,e){const t=N(n,"x","reverse");return I(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),An(t,e)}const T2=D({reverse4d_:k2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function E2(n){const t={x:N(n,"x","round")};return R.runKernel(pi,t)}const If=D({round_:E2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A2(n){const t={x:N(n,"x","rsqrt","float32")};return R.runKernel(fi,t)}const Nf=D({rsqrt_:A2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function R2(n){const t={x:N(n,"x","selu")};return R.runKernel(mi,t)}const Cf=D({selu_:R2});function D2(n,e,t,s,r,o=[1,1],a="NHWC"){const i=N(n,"x","separableConv2d"),l=N(e,"depthwiseFilter","separableConv2d"),u=N(t,"pointwiseFilter","separableConv2d");let c=i,h=!1;if(i.rank===3&&(h=!0,c=F(i,[1,i.shape[0],i.shape[1],i.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");I(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),I(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),I(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),I(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),I(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);const d=l.shape[2],p=l.shape[3];I(u.shape[2]===d*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*p}, but got ${u.shape[2]}.`);const f=Di(c,l,s,r,a,o),m=tr(f,u,1,"valid",a);return h?F(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const kf=D({separableConv2d_:D2});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function O2(n,e){const t=N(n,"x","setdiff1d"),s=N(e,"y","setdiff1d");I(t.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${s.dtype}).`),I(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),I(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);const r=await t.data(),o=await s.data(),a=new Set(o);let i=0;for(let c=0;c`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Te(s,[e],[t])}const Tc=D({slice1d_:z2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function M2(n,e,t){const s=N(n,"x","slice2d");return I(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Te(s,e,t)}const Af=D({slice2d_:M2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function B2(n,e,t){const s=N(n,"x","slice3d");return I(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Te(s,e,t)}const Ec=D({slice3d_:B2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function V2(n,e,t){const s=N(n,"x","slice4d");return I(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Te(s,e,t)}const Sa=D({slice4d_:V2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function W2(n,e=-1){const t=N(n,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);const s={logits:t},r={dim:e};return R.runKernel(uc,s,r)}const Ac=D({softmax_:W2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function U2(n){I(n.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);const e={input:n};return R.runKernel(cp,e)}const Rc=D({fft_:U2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function G2(n){I(n.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);const e={input:n};return R.runKernel(fp,e)}const Ia=D({ifft_:G2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function H2(n){const e=n.shape[n.shape.length-1],t=n.size/e;let s;if(e<=2){const r=F(n,[t,e]);s=Ia(r)}else{const r=[t,2*(e-1)],o=F($a(n),[t,e]),a=F(bc(n),[t,e]),i=An(Te(o,[0,1],[t,e-2]),1),l=O(An(Te(a,[0,1],[t,e-2]),1),pe(-1)),u=at([o,i],1),c=at([a,l],1),h=F(Js(u,c),[r[0],r[1]]);s=Ia(h)}if(s=$a(s),n.rank===3&&n.shape[0]!==0){const r=s,o=n.shape[0];s=F(s,[o,s.shape[0]/o,s.shape[1]]),r.dispose()}return s}const Rf=D({irfft_:H2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function j2(n,e,t=0){const r={x:N(n,"x","split")},o={numOrSizeSplits:e,axis:t};return R.runKernel(lc,r,o)}const on=D({split_:j2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function q2(n,e){I(n.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${n.dtype}`);let t=n.shape[n.shape.length-1];const s=n.size/t;let r;if(e!=null&&e0),g=n.shape.map(m=>m);g[n.shape.length-1]=e,r=Te(n,f,g),t=e}else if(e!=null&&e>t){const f=n.shape.map(g=>g);f[n.shape.length-1]=e-t,r=at([n,ct(f)],n.shape.length-1),t=e}else r=n;const o=Ee(r),a=F(Js(r,o),[s,t]),i=Rc(a),l=Math.floor(t/2)+1,u=$a(i),c=bc(i),h=on(u,[l,t-l],u.shape.length-1),d=on(c,[l,t-l],c.shape.length-1),p=r.shape.slice();return p[r.shape.length-1]=l,F(Js(h[0],d[0]),p)}const Dc=D({rfft_:q2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function K2(n,e){let t=N(n,"a","squaredDifference"),s=N(e,"b","squaredDifference");[t,s]=Ze(t,s),ye(t.shape,s.shape);const r={a:t,b:s},o={};return R.runKernel($i,r,o)}const Df=D({squaredDifference_:K2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X2(n,e){const t=N(n,"x","squeeze","string_or_numeric");return F(t,Es(t.shape,e).newShape)}const Jr=D({squeeze_:X2});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Y2(n,e=0){const t=ga(n,"tensors","stack","string_or_numeric");I(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&I(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");const s=t,r={axis:e};return R.runKernel(Yu,s,r)}const Xt=D({stack_:Y2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Z2(n,e=0){const s={x:N(n,"x","step")},r={alpha:e};return R.runKernel(ki,s,r)}const Fo=D({step_:Z2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function J2(n,e,t,s,r=0,o=0,a=0,i=0,l=0){const c={x:N(n,"x","stridedSlice","string_or_numeric")},h={begin:e,end:t,strides:s,beginMask:r,endMask:o,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return R.runKernel(Vp,c,h)}const Bw=D({stridedSlice_:J2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Q2(n){const t={x:N(n,"x","tan","float32")};return R.runKernel(Ii,t)}const Vw=D({tan_:Q2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pt(n,e){qr(n);const t=ls(n,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return lr(n,null,t,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tr(n,e,t){if(qr(n),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const s=ls(n,t);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return lr(n,e,s,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ww(n,e,t){if(qr(n),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const s=ls(n,t);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&e==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return lr(n,e,s,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eE(n,e,t){if(qr(n),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const s=ls(n,t);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&e==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return lr(n,e,s,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tE(n,e,t){if(qr(n),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const s=ls(n,t);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&e==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return lr(n,e,s,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nE(n,e,t){if(qr(n),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const s=ls(n,t);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&e==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return e=e||s,lr(n,e,s,t)}function Of(n,e,t){const s=e.rank>1?e.shape[e.rank-1]:1,r=e.rank>1?e.rank-1:1,o=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t.shape}, indices.shape: ${e.shape}, shape: ${n}, sliceDim: ${s}, and batchDim: ${r}.`;if(t.rank1?e.shape[s-1]:1,o=t.length;let a=1;for(let h=r;h= 0 but got ${e}`);if(e>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${e}`);const o={x:s},a={k:e,sorted:t},[i,l]=R.runKernel(Hp,o,a);return{values:i,indices:l}}const Uw=D({topk_:oE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aE(n,e=0,t=1,s,r){if(hn(n),s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const o=new vf(e,t,s,!0,r),a=ve(n,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");const s={x:t},r={axis:e},[o,a]=R.runKernel(qp,s,r);return{values:o,indices:a}}const Gw=D({unique_:iE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lE(n,e,t){const s=N(n,"x","unsortedSegmentSum"),r=N(e,"segmentIds","unsortedSegmentSum","int32");I(Rr(t),()=>"numSegments must be of dtype int");const o={x:s,segmentIds:r},a={numSegments:t};return R.runKernel(dc,o,a)}const Ff=D({unsortedSegmentSum_:lE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uE(n,e=0){const t=N(n,"x","unstack","string_or_numeric");I(e>=-t.shape.length&&e`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);const s={value:t},r={axis:e};return R.runKernel(hc,s,r)}const Rn=D({unstack_:uE});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cE(n,e){return bf(n,e,"right")}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hw(n,e=!0,t,s){return R.makeVariable(n,e,t,s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _c(n,e){const t=[];for(let o=0;o0,()=>"mask cannot be scalar"),Rt(i.slice(o,o+a),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let g=o;gi).reverse()),I(s.rank===e.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${e}.`),e.forEach(a=>{I(a>=0&&a`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${e}`)}),s.rank<=1)return s.clone();const r={x:s},o={perm:e};return s.dtype==="complex64"?z(()=>{let a=$a(s),i=bc(s);return a=R.runKernel(fo,{x:a},o),i=R.runKernel(fo,{x:i},o),t&&(i=Ge(i)),Js(a,i)}):R.runKernel(fo,r,o)}const ke=D({transpose_:fE});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mE(n,e,t,s,r=!0){const o=N(n,"v","movingAverage"),a=N(e,"x","movingAverage"),i=N(t,"decay","movingAverage");Ex(o,a),I(Ce(o.shape,a.shape),()=>"Shape mismatch in v and x");const l=pe(1),u=ae(l,i);let c=O(ae(a,o),u);if(r){I(s!=null,()=>"When using zeroDebias: true, step is required.");const h=N(s,"step","movingAverage");c=ce(c,ae(l,Ns(i,h)))}return Y(o,c)}const gE=D({movingAverage_:mE});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yE(n,e,t){hn(t);const s=N(n,"indices","scatterND","int32"),r=N(e,"updates","scatterND");Oc(r,s,t);const o={indices:s,updates:r},a={shape:t};return R.runKernel(Dp,o,a)}const bE=D({scatterND_:yE});function xE(n,e,t,s){if(n.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${n.dtype}.`);if(n.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${n.shape}.`);const r=n.rank>0?n.shape[0]:1,o=n.rank>1?n.shape[1]:1;if(t.length!==o)throw new Error(`outputShape has incorrect number of elements:, ${t.length}, should be: ${o}.`);const a=e.size;if(!(e.rank===0||e.rank===1&&a===r))throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${r}]`);if(e.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wE(n,e,t,s=0){hn(t);const r=N(n,"sparseIndices","sparseToDense","int32"),o=N(e,"sparseValues","sparseToDense","string_or_numeric"),a=N(s,"defaultValue","sparseToDense",o.dtype);xE(r,o,t,a);const i={sparseIndices:r,sparseValues:o,defaultValue:a},l={outputShape:t};return R.runKernel(Mp,i,l)}const vE=D({sparseToDense_:wE});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $E(n,e){const t=N(e,"indices","gatherND","int32"),r={params:N(n,"x","gatherND","string_or_numeric"),indices:t};return R.runKernel(pp,r)}const SE=D({gatherND_:$E});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IE(n,e){if(e==null)return n.shape.slice();if(Ce(n.shape,e))return e;if(n.shape.length===e.length){const t=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),I(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return n instanceof Re?r.clone():r;const o=IE(r,t),a=1-e,i=ce(Fi(Y(Zr(o,0,1,"float32",s),a)),a);return O(r,i)}const qw=D({dropout_:NE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kw(n){return Math.floor(Math.pow(2,Math.ceil(Math.log(n)/Math.log(2))))}function Lf(n,e,t){const s=1-n%2,r=new Float32Array(n);for(let o=0;o1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),I(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),Rt(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const o=s.shape[s.shape.length-1];I(t>0&&t<=o,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${o}), but got ${t}`);const a=await s.data(),i=await r.data(),[l,u]=[a.length/o,o],c=wt("bool",l);for(let h=0;hm.value-g.value),c[h]=0;for(let g=0;g`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),I(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),I(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);const u=o==="NHWC"?i.shape[3]:i.shape[1],c=o==="NHWC"?l.shape[3]:l.shape[1];I(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),I(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),Gt("conv2dDerFilter",r,a);const h={x:i,dy:l},d={strides:s,pad:r,dataFormat:o,dimRoundingMode:a,filterShape:t};return R.runKernel(Zd,h,d)}const Pf=D({conv2DBackpropFilter_:TE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fc(n,e,t){if(t==null||t==="linear")return n;if(t==="relu")return O(n,Fo(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Lc(n,e){let t=e;const s=it(n.shape,e.shape);return s.length>0&&(t=ie(t,s)),F(t,n.shape)}function Pc(n,e,t,s){if(e==="linear")return n;if(e==="relu")return hs(n);if(e==="elu")return Oi(n);if(e==="relu6")return Sf(n);if(e==="prelu")return kc(n,t);if(e==="leakyrelu")return xc(n,s);if(e==="sigmoid")return ss(n);throw new Error(`Unknown fused activation ${e}.`)}const zc=(n,e)=>!(n>0)||e==="linear";/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EE({x:n,filter:e,strides:t,pad:s,dataFormat:r="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",zc(R.state.gradientDepth,l)===!1){I(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let C=tr(n,e,t,s,r,o,a);return i!=null&&(C=Y(C,i)),Pc(C,l,u,c)}const h=N(n,"x","conv2d","float32"),d=N(e,"filter","conv2d","float32");let p=h,f=!1;h.rank===3&&(f=!0,p=F(h,[1,h.shape[0],h.shape[1],h.shape[2]])),I(p.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),I(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),Gt("fused conv2d",s,a);const g=r==="NHWC"?p.shape[3]:p.shape[1];I(d.shape[2]===g,()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${d.shape[2]}.`),I(Dt(t,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`);const m=$t(p.shape,d.shape,t,o,s,a);let y;i!=null&&(y=N(i,"bias","fused conv2d"),[y]=Ze(y,h),r==="NHWC"?ye(m.outShape,y.shape):(I(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),I(y.shape.length===0||y.shape[0]===m.outChannels||y.shape[0]===1,()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${m.outChannels})`)));let b;if(u!=null){const C=u.shape;if(I(C.length<=1||C.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${C.length}.`),C.length===1)I(C[0]===1||C[0]===m.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the number of output channels (${m.outChannels}).`);else if(C.length===3)try{ye(C,m.outShape)}catch{const A=`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the output shape of the conv2d (${m.outShape}).`;throw Error(A)}b=N(u,"prelu weights","fused conv2d")}const w=(C,E)=>{I(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);const[A,k,T,S]=E,_=Fc(C,T,l);I(er(o),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const P=uf(k.shape,_,A,t,s),V=Pf(k,_,A.shape,t,s),M=[P,V];if(S!=null){const W=Lc(S,_);M.push(W)}return M},x={x:p,filter:d,bias:y,preluActivationWeights:b},$={strides:t,pad:s,dataFormat:r,dilations:o,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Cs((E,A,k)=>{let T=R.runKernel(Fl,x,$);return k([A,E,T]),f&&(T=F(T,[T.shape[1],T.shape[2],T.shape[3]])),{value:T,gradFunc:w}})(p,d):Cs((E,A,k,T)=>{let S=R.runKernel(Fl,x,$);return T([A,E,S,k]),f&&(S=F(S,[S.shape[1],S.shape[2],S.shape[3]])),{value:S,gradFunc:w}})(p,d,y)}const Xw=D({fusedConv2d_:EE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AE(n,e,t,s,r,o=[1,1],a){let i=n;n.rank===3&&(i=F(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=e;l.rank===3&&(l=F(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const u={x:i,dy:l},c={strides:s,pad:r,dimRoundingMode:a,dilations:o,filterShape:t};return R.runKernel(rp,u,c)}const Yw=D({depthwiseConv2dNativeBackpropFilter_:AE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RE(n,e,t,s,r,o=[1,1],a){let i=e,l=!1;e.rank===3&&(l=!0,i=F(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const u={dy:i,filter:t},c={strides:s,pad:r,dimRoundingMode:a,dilations:o,inputShape:n},h=R.runKernel(op,u,c);return l?F(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Zw=D({depthwiseConv2dNativeBackpropInput_:RE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DE({x:n,filter:e,strides:t,pad:s,dataFormat:r="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(zc(R.state.gradientDepth,l)===!1){let $=Di(n,e,t,s,r,o,a);return i!=null&&($=Y($,i)),Pc($,l,u,c)}const h=N(n,"x","depthwiseConv2d","float32"),d=N(e,"filter","depthwiseConv2d","float32");let p=h,f=!1;h.rank===3&&(f=!0,p=F(h,[1,h.shape[0],h.shape[1],h.shape[2]])),I(p.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),I(d.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),I(p.shape[3]===d.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),o==null&&(o=[1,1]),I(Dt(t,o),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`),Gt("fused depthwiseConv2d",s,a);const g=$t(p.shape,d.shape,t,o,s,a,!0);let m;i!=null&&(m=N(i,"bias","fused conv2d"),[m]=Ze(m,h),ye(g.outShape,m.shape));let y;u!=null&&(y=N(u,"prelu weights","fused depthwiseConv2d"));const b=($,C)=>{I(er(o),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[E,A,k,T]=C,S=Fc($,k,l),_=Zw(A.shape,S,E,t,s,o,a),P=Yw(A,S,E.shape,t,s,o,a);if(T!=null){const V=Lc(m,S);return[_,P,V]}return[_,P]},w={x:p,filter:d,bias:m,preluActivationWeights:y},x={strides:t,pad:s,dataFormat:r,dilations:o,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Cs((C,E,A)=>{let k=R.runKernel(Ll,w,x);return A([E,C,k]),f&&(k=F(k,[k.shape[1],k.shape[2],k.shape[3]])),{value:k,gradFunc:b}})(p,d):Cs((C,E,A,k)=>{let T=R.runKernel(Ll,w,x);return k([E,C,T,A]),f&&(T=F(T,[T.shape[1],T.shape[2],T.shape[3]])),{value:T,gradFunc:b}})(p,d,m)}const OE=D({fusedDepthwiseConv2d_:DE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _E({a:n,b:e,transposeA:t=!1,transposeB:s=!1,bias:r,activation:o="linear",preluActivationWeights:a,leakyreluAlpha:i=.2}){if(zc(R.state.gradientDepth,o)===!1){let S=Ne(n,e,t,s);return r!=null&&(S=Y(S,r)),Pc(S,o,a,i)}let l=N(n,"a","fused matMul"),u=N(e,"b","fused matMul");[l,u]=Ze(l,u);const c=t?l.shape[l.rank-2]:l.shape[l.rank-1],h=s?u.shape[u.rank-1]:u.shape[u.rank-2],d=t?l.shape[l.rank-1]:l.shape[l.rank-2],p=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),g=u.shape.slice(0,-2),m=G(f),y=G(g);I(c===h,()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${s} must match.`);const w=ye(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([d,p]),x=t?F(l,[m,c,d]):F(l,[m,d,c]),$=s?F(u,[y,p,h]):F(u,[y,h,p]);let C;r!=null&&(C=N(r,"bias","fused matMul"),[C]=Ze(C,l),ye(w,C.shape));let E;a!=null&&(E=N(a,"prelu weights","fused matMul"));const A=(S,_)=>{const[P,V,M,W]=_,j=Fc(F(S,M.shape),M,o);let U,q;if(!t&&!s?(U=Ne(j,V,!1,!0),q=Ne(P,j,!0,!1)):!t&&s?(U=Ne(j,V,!1,!1),q=Ne(j,P,!0,!1)):t&&!s?(U=Ne(V,j,!1,!0),q=Ne(P,j,!1,!1)):(U=Ne(V,j,!0,!0),q=Ne(j,P,!0,!0)),r!=null){const K=Lc(W,j);return[U,q,K]}else return[U,q]},k={a:x,b:$,bias:C,preluActivationWeights:E},T={transposeA:t,transposeB:s,activation:o,leakyreluAlpha:i};return r==null?Cs((_,P,V)=>{const M=R.runKernel(_l,k,T);return V([_,P,M]),{value:F(M,w),gradFunc:A}})(x,$):Cs((_,P,V,M)=>{const W=R.runKernel(_l,k,T);return M([_,P,W,V]),{value:F(W,w),gradFunc:A}})(x,$,C)}const rd=D({fusedMatMul_:_E});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FE=Object.freeze(Object.defineProperty({__proto__:null,conv2d:Xw,depthwiseConv2d:OE,matMul:rd},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LE(n){return Lf(n,.54,.46)}const PE=D({hammingWindow_:LE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zE(n){return Lf(n,.5,.5)}const Jw=D({hannWindow_:zE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ME(n,e,t,s=!1,r=0){let o=0;const a=[];for(;o+e<=n.size;)a.push(Te(n,o,e)),o+=t;if(s)for(;o`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),I(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),I(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),I(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),I(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),I(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);const c={image:a,boxes:i,boxInd:l},h={method:r,extrapolationValue:o,cropSize:s};return R.runKernel(tp,c,h)}const UE=D({cropAndResize_:WE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GE(n){const e=N(n,"image","flipLeftRight","float32");I(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);const t={image:e};return R.runKernel(dp,t,{})}const HE=D({flipLeftRight_:GE});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jE(n){const e=N(n,"image","grayscaleToRGB"),t=e.rank-1,s=e.shape[t];I(e.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${e.rank}.`),I(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);const r=new Array(e.rank);return r.fill(1,0,t),r[t]=3,kn(e,r)}const qE=D({grayscaleToRGB_:jE});/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KE(n){const e=N(n,"image","RGBToGrayscale"),t=e.rank-1,s=e.shape[t];I(e.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${e.rank}.`),I(s===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`);const r=e.dtype,o=ee(e,"float32"),a=Pt([.2989,.587,.114]);let i;switch(e.rank){case 2:i=po("ij,j->i",o,a);break;case 3:i=po("ijk,k->ij",o,a);break;case 4:i=po("ijkl,l->ijk",o,a);break;case 5:i=po("ijklm,m->ijkl",o,a);break;case 6:i=po("ijklmn,n->ijklm",o,a);break;default:throw new Error("Not a valid tensor rank.")}return i=Lt(i,-1),ee(i,r)}const XE=D({rgbToGrayscale_:KE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YE(n,e,t=0,s=.5){const r=N(n,"image","rotateWithOffset","float32");I(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);const o={image:r},a={radians:e,fillValue:t,center:s};return R.runKernel(Kp,o,a)}const ZE=D({rotateWithOffset_:YE});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lo(n,e,t,s,r,o){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),o==null&&(o=0);const a=n.shape[0];return t=Math.min(t,a),I(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),I(n.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),I(n.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),I(e.rank===1,()=>"scores must be a 1D tensor"),I(e.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`),I(0<=o&&o<=1,()=>`softNmsSigma must be in [0, 1], but was '${o}'`),{maxOutputSize:t,iouThreshold:s,scoreThreshold:r,softNmsSigma:o}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JE(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY){const o=N(n,"boxes","nonMaxSuppression","float32"),a=N(e,"scores","nonMaxSuppression","float32"),i=Lo(o,a,t,s,r);t=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;const l={maxOutputSize:t,iouThreshold:s,scoreThreshold:r};return R.runKernel($p,{boxes:o,scores:a},l)}const QE=D({nonMaxSuppression_:JE});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eA(n,e,t){const s=tA(n,e,t),r=s<0?-(s+1):s;n.splice(r,0,e)}function tA(n,e,t){return sA(n,e,t||nA)}function nA(n,e){return n>e?1:n>>1);const i=t(e,n[o]);i>0?s=o+1:(r=o,a=!i)}return a?s:-s-1}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mc(n,e,t,s,r){return zf(n,e,t,s,r,0)}function Bc(n,e,t,s,r,o){return zf(n,e,t,s,r,0,!1,o,!0)}function Vc(n,e,t,s,r,o){return zf(n,e,t,s,r,o,!0)}function zf(n,e,t,s,r,o,a=!1,i=!1,l=!1){const u=[];for(let m=0;mr&&u.push({score:e[m],boxIndex:m,suppressBeginIndex:0});u.sort(Py);const c=o>0?-.5/o:0,h=[],d=[];for(;h.length0;){const m=u.pop(),{score:y,boxIndex:b,suppressBeginIndex:w}=m;if(y=w;--$){const C=rA(n,b,h[$]);if(C>=s){x=!0;break}if(m.score=m.score*oA(s,c,C),m.score<=r)break}m.suppressBeginIndex=h.length,x||(m.score===y?(h.push(b),d.push(m.score)):m.score>r&&eA(u,m,Py))}const p=h.length,f=t-p;i&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const g={selectedIndices:h};return a&&(g.selectedScores=d),l&&(g.validOutputs=p),g}function rA(n,e,t){const s=n.subarray(e*4,e*4+4),r=n.subarray(t*4,t*4+4),o=Math.min(s[0],s[2]),a=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),p=(i-o)*(l-a),f=(h-u)*(d-c);if(p<=0||f<=0)return 0;const g=Math.max(o,u),m=Math.max(a,c),y=Math.min(i,h),b=Math.min(l,d),w=Math.max(y-g,0)*Math.max(b-m,0);return w/(p+f-w)}function oA(n,e,t){const s=Math.exp(e*t*t);return t<=n?s:0}function Py(n,e){return n.score-e.score||n.score===e.score&&e.boxIndex-n.boxIndex}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function aA(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY){const o=N(n,"boxes","nonMaxSuppressionAsync"),a=N(e,"scores","nonMaxSuppressionAsync"),i=Lo(o,a,t,s,r);t=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;const l=await Promise.all([o.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:h}=Mc(u,c,t,s,r);return o!==n&&o.dispose(),a!==e&&a.dispose(),Pt(h,"int32")}const iA=aA;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lA(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,o=0){const a=N(n,"boxes","nonMaxSuppression"),i=N(e,"scores","nonMaxSuppression"),l=Lo(a,i,t,s,r,o);t=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,o=l.softNmsSigma;const u={boxes:a,scores:i},c={maxOutputSize:t,iouThreshold:s,scoreThreshold:r,softNmsSigma:o},h=R.runKernel(Ip,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}const uA=D({nonMaxSuppressionWithScore_:lA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function cA(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,o=0){const a=N(n,"boxes","nonMaxSuppressionAsync"),i=N(e,"scores","nonMaxSuppressionAsync"),l=Lo(a,i,t,s,r,o);t=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,o=l.softNmsSigma;const u=await Promise.all([a.data(),i.data()]),c=u[0],h=u[1],{selectedIndices:d,selectedScores:p}=Vc(c,h,t,s,r,o);return a!==n&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Pt(d,"int32"),selectedScores:Pt(p)}}const hA=cA;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dA(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,o=!1){const a=N(n,"boxes","nonMaxSuppression"),i=N(e,"scores","nonMaxSuppression"),l=Lo(a,i,t,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,d={boxes:a,scores:i},p={maxOutputSize:u,iouThreshold:c,scoreThreshold:h,padToMaxOutputSize:o},f=R.runKernel(Sp,d,p);return{selectedIndices:f[0],validOutputs:f[1]}}const pA=D({nonMaxSuppressionPadded_:dA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function fA(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,o=!1){const a=N(n,"boxes","nonMaxSuppressionAsync"),i=N(e,"scores","nonMaxSuppressionAsync"),l=Lo(a,i,t,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,p]=await Promise.all([a.data(),i.data()]),{selectedIndices:f,validOutputs:g}=Bc(d,p,u,c,h,o);return a!==n&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Pt(f,"int32"),validOutputs:pe(g,"int32")}}const mA=fA;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gA(n,e,t=!1,s=!1){const r=N(n,"images","resizeBilinear");I(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),I(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),I(s===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let o=r,a=!1;r.rank===3&&(a=!0,o=F(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const i={images:o},l={alignCorners:t,halfPixelCenters:s,size:e},u=R.runKernel(nc,i,l);return a?F(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const e0=D({resizeBilinear_:gA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yA(n,e,t=!1,s=!1){const r=N(n,"images","resizeNearestNeighbor");I(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),I(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),I(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),I(s===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let o=r,a=!1;r.rank===3&&(a=!0,o=F(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const i={images:o},l={alignCorners:t,halfPixelCenters:s,size:e},u=R.runKernel(tc,i,l);return a?F(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const t0=D({resizeNearestNeighbor_:yA});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bA(n,e="binary",t=!1,s=.5){const r=N(n,"image","threshold"),o=.2989,a=.587,i=.114,l=r.shape[0]*r.shape[1];let u=O(Pt([s]),255),c,h,d,p;if(I(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),I(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),I(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),I(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),r.shape[2]===3){[c,h,d]=on(r,[1,1,1],-1);const m=O(c,o),y=O(h,a),b=O(d,i);p=Y(Y(m,y),b)}else p=n;if(e==="otsu"){const m=lw(ee(If(p),"int32"),xn([]),256);u=xA(m,l)}const f=t?Yr(p,u):Jt(p,u);return ee(O(f,255),"int32")}function xA(n,e){let t=Pt([-1]),s=Pt([0]),r=Pt([0]),o,a,i,l,u,c;for(let h=0;h`Error in transform: image must be rank 4,but got rank ${a.rank}.`),I(i.rank===2&&(i.shape[0]===a.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),I(o==null||o.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${o}.`);const l={image:a,transforms:i},u={interpolation:t,fillMode:s,fillValue:r,outputShape:o};return R.runKernel(jp,l,u)}const $A=D({transform_:vA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SA(n,e,t){const s=N(n,"a","bandPart");I(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const r=s.shape,[o,a]=s.shape.slice(-2);let i,l;typeof e=="number"?(I(e%1===0,()=>`bandPart(): numLower must be an integer, got ${e}.`),I(e<=o,()=>`bandPart(): numLower (${e}) must not be greater than the number of rows (${o}).`),i=N(e<0?o:e,"numLower","bandPart")):(I(e.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),i=Tt(wa(e,0),o,zr(e,o))),typeof t=="number"?(I(t%1===0,()=>`bandPart(): numUpper must be an integer, got ${t}.`),I(t<=a,()=>`bandPart(): numUpper (${t}) must not be greater than the number of columns (${a}).`),l=N(t<0?a:t,"numUpper","bandPart")):(I(t.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=Tt(wa(t,0),a,zr(t,a)));const u=F(So(0,o,1,"int32"),[-1,1]),c=So(0,a,1,"int32"),h=ae(u,c),d=Gn(Yr(h,i),hr(h,Ge(l))),p=ct([o,a],s.dtype);return F(Xt(Rn(F(s,[-1,o,a])).map(f=>Tt(d,f,p))),r)}const IA=D({bandPart_:SA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NA(n){let e;if(Array.isArray(n)){e=!1,I(n!=null&&n.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const r=n[0].shape[0];for(let o=1;o`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[o].shape[0]} vs. ${r})`)}else e=!0,n=on(n,n.shape[0],0).map(r=>Jr(r,[0]));I(n.length<=n[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);const t=[],s=n;for(let r=0;r{let o=s[r];if(r>0)for(let a=0;a=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),n.rank===2)return zy(n,e);{const t=n.shape.slice(0,n.shape.length-2).reduce((l,u)=>l*u),s=Rn(F(n,[t,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),r=[],o=[];s.forEach(l=>{const[u,c]=zy(l,e);r.push(u),o.push(c)});const a=F(Xt(r,0),n.shape),i=F(Xt(o,0),n.shape);return[a,i]}}function zy(n,e=!1){return R.tidy(()=>{I(n.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);const t=n.shape[0],s=n.shape[1];let r=mf(t),o=vs(n);const a=Tr([[1]],[1,1]);let i=vs(a);const l=t>=s?s:t;for(let u=0;u{const p=Te(o,[u,u],[t-u,1]),f=_i(p),g=Te(o,[u,u],[1,1]),m=Tt(Jt(g,0),Tr([[-1]]),Tr([[1]])),y=ae(g,O(m,f)),b=ce(p,y);b.shape[0]===1?i=vs(a):i=at([a,Te(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);const w=Ge(ce(Ne(m,y),f)),x=Te(o,[u,0],[t-u,s]),$=O(w,i),C=ke(i);if(u===0)o=ae(x,Ne($,Ne(C,x)));else{const k=ae(x,Ne($,Ne(C,x)));o=at([Te(o,[0,0],[u,s]),k],0)}const E=ke($),A=Te(r,[0,u],[t,r.shape[1]-u]);if(u===0)r=ae(A,Ne(Ne(A,i),E));else{const k=ae(A,Ne(Ne(A,i),E));r=at([Te(r,[0,0],[t,u]),k],1)}return[i,o,r]}),be([c,h,d])}return!e&&t>s&&(r=Te(r,[0,0],[t,s]),o=Te(o,[0,0],[s,s])),[r,o]})}const TA=D({qr_:kA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var qt;(function(n){n[n.NONE=0]="NONE",n[n.MEAN=1]="MEAN",n[n.SUM=2]="SUM",n[n.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(qt||(qt={}));function EA(n,e,t=qt.SUM_BY_NONZERO_WEIGHTS){const s=N(n,"losses","computeWeightedLoss");let r=null;e!=null&&(r=N(e,"weights","computeWeightedLoss"));const o=r==null?s:O(s,r);if(t===qt.NONE)return o;if(t===qt.SUM)return ie(o);if(t===qt.MEAN){if(r==null)return et(o);{const a=s.size/r.size,i=ce(ie(o),ie(r));return a>1?ce(i,pe(a)):i}}if(t===qt.SUM_BY_NONZERO_WEIGHTS){if(r==null)return ce(ie(o),pe(s.size));{const a=O(r,rn(s.shape)),i=ee(ie($o(a,pe(0))),"float32");return ce(ie(o),i)}}throw Error(`Unknown reduction: ${t}`)}const _s=D({computeWeightedLoss_:EA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AA(n,e,t,s=qt.SUM_BY_NONZERO_WEIGHTS){const r=N(n,"labels","absoluteDifference"),o=N(e,"predictions","absoluteDifference");let a=null;t!=null&&(a=N(t,"weights","absoluteDifference")),Rt(r.shape,o.shape,"Error in absoluteDifference: ");const i=lt(ae(r,o));return _s(i,a,s)}const RA=D({absoluteDifference_:AA});function DA(n,e,t,s,r=qt.SUM_BY_NONZERO_WEIGHTS){const o=N(n,"labels","cosineDistance"),a=N(e,"predictions","cosineDistance");let i=null;s!=null&&(i=N(s,"weights","cosineDistance")),Rt(o.shape,a.shape,"Error in cosineDistance: ");const l=pe(1),u=ae(l,ie(O(o,a),t,!0));return _s(u,i,r)}const OA=D({cosineDistance_:DA});function _A(n,e,t,s=qt.SUM_BY_NONZERO_WEIGHTS){let r=N(n,"labels","hingeLoss");const o=N(e,"predictions","hingeLoss");let a=null;t!=null&&(a=N(t,"weights","hingeLoss")),Rt(r.shape,o.shape,"Error in hingeLoss: ");const i=pe(1);r=ae(O(pe(2),r),i);const l=hs(ae(i,O(r,o)));return _s(l,a,s)}const FA=D({hingeLoss_:_A});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LA(n,e,t,s=1,r=qt.SUM_BY_NONZERO_WEIGHTS){const o=N(n,"labels","huberLoss"),a=N(e,"predictions","huberLoss");let i=null;t!=null&&(i=N(t,"weights","huberLoss")),Rt(o.shape,a.shape,"Error in huberLoss: ");const l=pe(s),u=lt(ae(a,o)),c=zr(u,l),h=ae(u,c),d=Y(O(pe(.5),ze(c)),O(l,h));return _s(d,i,r)}const PA=D({huberLoss_:LA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zA(n,e,t,s=1e-7,r=qt.SUM_BY_NONZERO_WEIGHTS){const o=N(n,"labels","logLoss"),a=N(e,"predictions","logLoss");let i=null;t!=null&&(i=N(t,"weights","logLoss")),Rt(o.shape,a.shape,"Error in logLoss: ");const l=pe(1),u=pe(s),c=Ge(O(o,vn(Y(a,u)))),h=O(ae(l,o),vn(Y(ae(l,a),u))),d=ae(c,h);return _s(d,i,r)}const MA=D({logLoss_:zA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BA(n,e,t,s=qt.SUM_BY_NONZERO_WEIGHTS){const r=N(n,"labels","meanSquaredError"),o=N(e,"predictions","meanSquaredError");let a=null;t!=null&&(a=N(t,"weights","meanSquaredError")),Rt(r.shape,o.shape,"Error in meanSquaredError: ");const i=Df(r,o);return _s(i,a,s)}const VA=D({meanSquaredError_:BA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WA(n,e){const t=N(n,"labels","sigmoidCrossEntropyWithLogits"),s=N(e,"logits","sigmoidCrossEntropyWithLogits");Rt(t.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const r=hs(s),o=O(s,t),a=wc(un(Ge(lt(s))));return Y(ae(r,o),a)}function UA(n,e,t,s=0,r=qt.SUM_BY_NONZERO_WEIGHTS){let o=N(n,"multiClassLabels","sigmoidCrossEntropy");const a=N(e,"logits","sigmoidCrossEntropy");let i=null;if(t!=null&&(i=N(t,"weights","sigmoidCrossEntropy")),Rt(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),s>0){const u=pe(s),c=pe(1),h=pe(.5);o=Y(O(o,ae(c,u)),O(h,u))}const l=WA(o,a);return _s(l,i,r)}const GA=D({sigmoidCrossEntropy_:UA});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HA(n,e,t=-1){if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${e.rank} and dim was ${t}`);return Cs((r,o,a)=>{const l=$c(o,[t],!0),u=ae(ee(o,"float32"),l);a([r,u]);const c=Ge(O(u,r));return{value:ie(c,[t]),gradFunc:(p,f)=>{const[g,m]=f,y=nt(p.shape,[t]);return[O(F(p,y),ae(ee(g,"float32"),un(m))),O(F(p,y),ae(un(m),ee(g,"float32")))]}}})(n,e)}function jA(n,e,t,s=0,r=qt.SUM_BY_NONZERO_WEIGHTS){let o=N(n,"onehotLabels","softmaxCrossEntropy");const a=N(e,"logits","softmaxCrossEntropy");let i=null;if(t!=null&&(i=N(t,"weights","softmaxCrossEntropy")),Rt(o.shape,a.shape,"Error in softmaxCrossEntropy: "),s>0){const u=pe(s),c=pe(1),h=pe(o.shape[1]);o=Y(O(o,ae(c,u)),ce(u,h))}const l=HA(o,a);return _s(l,i,r)}const qA=D({softmaxCrossEntropy_:jA});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KA(n,e,t,s){const r=N(n,"indices","sparseFillEmptyRows","int32"),o=N(e,"values","sparseFillEmptyRows"),a=N(t,"denseShape","sparseFillEmptyRows","int32"),i=N(s,"defaultValue","sparseFillEmptyRows",o.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape + ${r.shape}`);if(o.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${o.shape}`);if(a.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${a.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const l={indices:r,values:o,denseShape:a,defaultValue:i},u=R.runKernel(Fp,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}const XA=D({sparseFillEmptyRows_:KA});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YA(n,e,t){const s=N(n,"inputIndices","sparseReshape","int32"),r=N(e,"inputShape","sparseReshape","int32"),o=N(t,"newShape","sparseReshape","int32");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape + ${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(o.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${o.shape}`);const a={inputIndices:s,inputShape:r,newShape:o},i=R.runKernel(Lp,a);return{outputIndices:i[0],outputShape:i[1]}}const ZA=D({sparseReshape_:YA});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JA(n,e,t){const s=N(n,"data","sparseSegmentMean"),r=N(e,"indices","sparseSegmentMean","int32"),o=N(t,"segmentIds","sparseSegmentMean","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape + ${r.shape}`);if(o.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape + ${o.shape}`);const a={data:s,indices:r,segmentIds:o};return R.runKernel(Pp,a)}const QA=D({sparseSegmentMean_:JA});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eR(n,e,t){const s=N(n,"data","sparseSegmentSum"),r=N(e,"indices","sparseSegmentSum","int32"),o=N(t,"segmentIds","sparseSegmentSum","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape + ${r.shape}`);if(o.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape + ${o.shape}`);const a={data:s,indices:r,segmentIds:o};return R.runKernel(zp,a)}const tR=D({sparseSegmentSum_:eR});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nR(n,e,t,s,r,o,a,i){const l=N(n,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);const u=N(e,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");const c={separator:t,nGramWidths:s,leftPad:r,rightPad:o,padWidth:a,preserveShortSequences:i},h={data:l,dataSplits:u},d=R.runKernel(Wp,h,c);return{nGrams:d[0],nGramsSplits:d[1]}}const sR=D({stringNGrams_:nR});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rR(n,e,t=!0){const s=N(n,"input","stringSplit","string"),r=N(e,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);const o={skipEmpty:t},a={input:s,delimiter:r},i=R.runKernel(Up,a,o);return{indices:i[0],values:i[1],shape:i[2]}}const oR=D({stringSplit_:rR});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aR(n,e){const t=N(n,"input","stringToHashBucketFast","string"),s={numBuckets:e};if(e<=0)throw new Error("Number of buckets must be at least 1");const r={input:t};return R.runKernel(Gp,r,s)}const iR=D({stringToHashBucketFast_:aR});/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lR(n,e,t,s=!0){const r=N(n,"input","staticRegexReplace","string"),o={pattern:e,rewrite:t,replaceGlobal:s};return R.runKernel(cc,{x:r},o)}const uR=D({staticRegexReplace_:lR});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cR={fft:Rc,ifft:Ia,rfft:Dc,irfft:Rf},hR={hammingWindow:PE,hannWindow:Jw,frame:Qw,stft:VE},Bn={flipLeftRight:HE,grayscaleToRGB:qE,resizeNearestNeighbor:t0,resizeBilinear:e0,rgbToGrayscale:XE,rotateWithOffset:ZE,cropAndResize:UE,nonMaxSuppression:QE,nonMaxSuppressionAsync:iA,nonMaxSuppressionWithScore:uA,nonMaxSuppressionWithScoreAsync:hA,nonMaxSuppressionPadded:pA,nonMaxSuppressionPaddedAsync:mA,threshold:wA,transform:$A},n0={bandPart:IA,gramSchmidt:CA,qr:TA},dR={absoluteDifference:RA,computeWeightedLoss:_s,cosineDistance:OA,hingeLoss:FA,huberLoss:PA,logLoss:MA,meanSquaredError:VA,sigmoidCrossEntropy:GA,softmaxCrossEntropy:qA},pR={sparseFillEmptyRows:XA,sparseReshape:ZA,sparseSegmentMean:QA,sparseSegmentSum:tR},fR={stringNGrams:sR,stringSplit:oR,stringToHashBucketFast:iR,staticRegexReplace:uR};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mR=new Map,od=new Map;class Qr{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class mn{constructor(){this.classNameMap={}}static getMap(){return mn.instance==null&&(mn.instance=new mn),mn.instance}static register(e){mn.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Z(n,e,t){I(n.className!=null,()=>"Class being registered does not have the static className property defined."),I(typeof n.className=="string",()=>"className is required to be a string, but got type "+typeof n.className),I(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof e>"u"&&(e="Custom"),typeof t>"u"&&(t=n.className);const s=t,r=e+">"+s;return mn.register(n),mR.set(r,n),od.set(n,r),n}function gR(n){return od.has(n)?od.get(n):n.className}const DJ=Object.freeze(Object.defineProperty({__proto__:null,Serializable:Qr,SerializationMap:mn,getRegisteredName:gR,registerClass:Z},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fr extends Qr{minimize(e,t=!1,s){const{value:r,grads:o}=this.computeGradients(e,s);if(s!=null){const a=s.map(i=>({name:i.name,tensor:o[i.name]}));this.applyGradients(a)}else this.applyGradients(o);return be(o),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Rk(e,t)}dispose(){this.iterations_!=null&&be(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:pe(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(fr,Symbol.hasInstance,{value:n=>n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class s0 extends fr{static get className(){return"Adadelta"}constructor(e,t,s=null){super(),this.learningRate=e,this.rho=t,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=R.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const o=R.registeredVariables[s],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${s}/accum_grad`,variable:z(()=>Ee(o).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${s}/accum_var`,variable:z(()=>Ee(o).variable(a))});const i=Array.isArray(e)?e[r].tensor:e[s];if(i==null)return;const l=this.accumulatedGrads[r].variable,u=this.accumulatedUpdates[r].variable;z(()=>{const c=Y(O(l,this.rho),O(ze(i),1-this.rho)),h=O(ce(At(Y(u,this.epsilon)),At(Y(l,this.epsilon))),i),d=Y(O(u,this.rho),O(ze(h),1-this.rho));l.assign(c),u.assign(d);const p=Y(O(h,-this.learningRate),o);o.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(be(this.accumulatedGrads.map(e=>e.variable)),be(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,s=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class r0 extends fr{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const o=R.registeredVariables[s];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${s}/accumulator`,variable:z(()=>Do(o.shape,this.initialAccumulatorValue).variable(!1))});const a=Array.isArray(e)?e[r].tensor:e[s];if(a==null)return;const i=this.accumulatedGrads[r].variable;z(()=>{const l=Y(i,ze(a));i.assign(l);const u=Y(O(ce(a,At(Y(l,R.backend.epsilon()))),-this.learningRate),o);o.assign(u)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&be(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulatedGrads=e.map(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class o0 extends fr{static get className(){return"Adam"}constructor(e,t,s,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],z(()=>{this.accBeta1=pe(t).variable(),this.accBeta2=pe(s).variable()}),r==null&&(this.epsilon=R.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);z(()=>{const s=ae(1,this.accBeta1),r=ae(1,this.accBeta2);t.forEach((o,a)=>{const i=R.registeredVariables[o],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${o}/m`,variable:z(()=>Ee(i).variable(l))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${o}/v`,variable:z(()=>Ee(i).variable(l))});const u=Array.isArray(e)?e[a].tensor:e[o];if(u==null)return;const c=this.accumulatedFirstMoment[a].variable,h=this.accumulatedSecondMoment[a].variable,d=Y(O(c,this.beta1),O(u,1-this.beta1)),p=Y(O(h,this.beta2),O(ze(u),1-this.beta2)),f=ce(d,s),g=ce(p,r);c.assign(d),h.assign(p);const m=Y(O(ce(f,Y(At(g),this.epsilon)),-this.learningRate),i);i.assign(m)}),this.accBeta1.assign(O(this.accBeta1,this.beta1)),this.accBeta2.assign(O(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&be(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&be(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),z(()=>{this.accBeta1.assign(Ns(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ns(this.beta2,this.iterations_+1))});const t=e.length/2,s=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class a0 extends fr{static get className(){return"Adamax"}constructor(e,t,s,r=null,o=0){super(),this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=r,this.decay=o,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],z(()=>{this.iteration=pe(0).variable(),this.accBeta1=pe(t).variable()}),r==null&&(this.epsilon=R.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);z(()=>{const s=ae(1,this.accBeta1),r=ce(-this.learningRate,Y(O(this.iteration,this.decay),1));t.forEach((o,a)=>{const i=R.registeredVariables[o],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${o}/m`,variable:Ee(i).variable(l)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${o}/v`,variable:Ee(i).variable(l)});const u=Array.isArray(e)?e[a].tensor:e[o];if(u==null)return;const c=this.accumulatedFirstMoment[a].variable,h=this.accumulatedWeightedInfNorm[a].variable,d=Y(O(c,this.beta1),O(u,1-this.beta1)),p=O(h,this.beta2),f=lt(u),g=Os(p,f);c.assign(d),h.assign(g);const m=Y(O(ce(r,s),ce(d,Y(g,this.epsilon))),i);i.assign(m)}),this.iteration.assign(Y(this.iteration,1)),this.accBeta1.assign(O(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&be(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&be(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Mf extends fr{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const o=Array.isArray(e)?e[r].tensor:e[s];if(o==null)return;const a=R.registeredVariables[s];z(()=>{const i=Y(O(this.c,o),a);a.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=bt(pe(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class i0 extends Mf{static get className(){return"Momentum"}constructor(e,t,s=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=s,this.accumulations=[],this.m=pe(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const o=R.registeredVariables[s];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${s}/momentum`,variable:z(()=>Ee(o).variable(!1))});const a=this.accumulations[r].variable,i=Array.isArray(e)?e[r].tensor:e[s];i!=null&&z(()=>{let l;const u=Y(O(this.m,a),i);this.useNesterov?l=Y(O(this.c,Y(i,O(u,this.m))),o):l=Y(O(this.c,u),o),a.assign(u),o.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&be(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulations=e.map(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class l0 extends fr{static get className(){return"RMSProp"}constructor(e,t=.9,s=0,r=null,o=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=s,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=o,r==null&&(this.epsilon=R.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const o=R.registeredVariables[s],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${s}/rms`,variable:z(()=>Ee(o).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${s}/momentum`,variable:z(()=>Ee(o).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${s}/mg`,variable:z(()=>Ee(o).variable(a))});const i=Array.isArray(e)?e[r].tensor:e[s];if(i==null)return;const l=this.accumulatedMeanSquares[r].variable,u=this.accumulatedMoments[r].variable;z(()=>{const c=Y(O(l,this.decay),O(ze(i),1-this.decay));if(this.centered){const h=this.accumulatedMeanGrads[r].variable,d=Y(O(h,this.decay),O(i,1-this.decay)),p=ce(O(i,this.learningRate),At(ae(c,Y(ze(d),this.epsilon)))),f=Y(O(u,this.momentum),p);l.assign(c),h.assign(d),u.assign(f);const g=ae(o,f);o.assign(g)}else{const h=Y(O(l,this.decay),O(ze(i),1-this.decay)),d=Y(O(u,this.momentum),ce(O(i,this.learningRate),At(Y(h,this.epsilon))));l.assign(h),u.assign(d);const p=ae(o,d);o.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&be(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&be(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&be(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,s=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yR=[s0,r0,o0,a0,i0,l0,Mf];function bR(){for(const n of yR)Z(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xR="model",wR=".json",vR=".weights.bin";function My(n){return new Promise(e=>setTimeout(e)).then(n)}class Mr{constructor(e){if(!B().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Mr.URL_SCHEME)&&(e=e.slice(Mr.URL_SCHEME.length)),(e==null||e.length===0)&&(e=xR),this.modelJsonFileName=e+wR,this.weightDataFileName=e+vR}async save(e){if(typeof document>"u")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=Kn.join(e.weightData),s=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const r=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],o=Mx(e,r),a=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),i=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(i.download=this.modelJsonFileName,i.href=a,await My(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const l=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;l.download=this.weightDataFileName,l.href=s,await My(()=>l.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ei(e)}}}}Mr.URL_SCHEME="downloads://";class $R{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{const s=new FileReader;s.onload=r=>{const o=JSON.parse(r.target.result),a=o.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(o.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}const l=sf(o,u=>this.loadWeights(u));e(l)},s.onerror=r=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),s.readAsText(this.jsonFile)})}loadWeights(e){const t=[],s=[];for(const a of e)t.push(...a.weights),s.push(...a.paths);const r=this.checkManifestAndWeightFiles(e),o=s.map(a=>this.loadWeightsFile(a,r[a]));return Promise.all(o).then(a=>[t,a])}loadWeightsFile(e,t){return new Promise((s,r)=>{const o=new FileReader;o.onload=a=>{const i=a.target.result;s(i)},o.onerror=a=>r(`Failed to weights data from file of path '${e}'.`),o.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],s=this.weightsFiles.map(o=>Ty(o.name)),r={};for(const o of e)o.paths.forEach(a=>{const i=Ty(a);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),s.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);r[a]=this.weightsFiles[s.indexOf(i)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}const SR=n=>B().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Mr.URL_SCHEME)?IR(n.slice(Mr.URL_SCHEME.length)):null;Xe.registerSaveRouter(SR);function IR(n="model"){return new Mr(n)}function NR(n){return new $R(n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function By(n,e,t,s){a(n),t=t??0,s=s??1,i(t,s);let r=0;const o=l=>(l.then(u=>{const c=t+ ++r/n.length*(s-t);return e(c),u}),l);function a(l){I(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){I(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),I(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),I(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(n.map(o))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function u0(n,e){e==null&&(e={});const t=e.fetchFunc==null?B().platform.fetch:e.fetchFunc,s=n.map(h=>t(h,e.requestInit,{isBinary:!0})),i=(e.onProgress==null?await Promise.all(s):await By(s,e.onProgress,0,.5)).map(h=>h.arrayBuffer());return e.onProgress==null?await Promise.all(i):await By(i,e.onProgress,.5,1)}function CR(n,e){var t;const s=e.fetchFunc==null?B().platform.fetch:e.fetchFunc;let r=0,o;return(t=e.onProgress)===null||t===void 0||t.call(e,0),new ReadableStream({pull:async a=>{for(var i;ru0(a,{requestInit:s}))(n,e,t)}function h0(n){return async(e,t="",s)=>{const r=e.map(()=>!1),o={},a=s!=null?s.map(()=>!1):[],i=[];if(e.forEach((p,f)=>{let g=0;p.weights.forEach(m=>{const y="quantization"in m?m.quantization.dtype:m.dtype,b=Dr[y]*G(m.shape),w=()=>{r[f]=!0,o[f]==null&&(o[f]=[]),o[f].push({manifestEntry:m,groupOffset:g,sizeBytes:b})};s!=null?s.forEach((x,$)=>{x===m.name&&(w(),a[$]=!0)}):w(),i.push(m.name),g+=b})}),!a.every(p=>p)){const p=s.filter((f,g)=>!a[g]);throw new Error(`Could not find weights in manifest with names: ${p.join(", ")}. +Manifest JSON has weights with names: ${i.join(", ")}.`)}const l=r.reduce((p,f,g)=>(f&&p.push(g),p),[]),u=[];l.forEach(p=>{e[p].paths.forEach(f=>{const g=t+(t.endsWith("/")?"":"/")+f;u.push(g)})});const c=await n(u),h={};let d=0;return l.forEach(p=>{const f=e[p].paths.length,g=new Kn(c.slice(d,d+f));o[p].forEach(y=>{const b=g.slice(y.groupOffset,y.groupOffset+y.sizeBytes),w=ef(b,[y.manifestEntry]);for(const x in w)h[x]=w[x]}),d+=f}),h}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kR="application/octet-stream",TR="application/json";class Bf{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(I(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=B().platform.fetch,I(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&I(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const s=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=Mx(e,s);if(t.body.append("model.json",new Blob([JSON.stringify(r)],{type:TR}),"model.json"),e.weightData!=null){const a=Kn.join(e.weightData);t.body.append("model.weights.bin",new Blob([a],{type:kR}),"model.weights.bin")}const o=await this.fetch(this.path,t);if(o.ok)return{modelArtifactsInfo:Ei(e),responses:[o]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${o.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch{let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}const s=t.modelTopology,r=t.weightsManifest;if(s==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();const e=await this.loadModelJSON();return sf(e,t=>this.loadWeights(t))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),s=Ml(e.weightsManifest),r=()=>CR(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:s,getWeightStream:r})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[s,r]=ER(t),o=this.weightPathPrefix||s,a=[],i=[];for(const l of e)for(const u of l.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):a.push(o+u+r);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){const t=await this.getWeightUrls(e),s=Ml(e),r=await u0(t,this.loadOptions);return[s,r]}}Bf.URL_SCHEME_REGEX=/^https?:\/\//;function ER(n){const e=n.lastIndexOf("/"),t=n.lastIndexOf("?"),s=n.substring(0,e),r=t>e?n.substring(t):"";return[s+"/",r]}function ad(n){return n.match(Bf.URL_SCHEME_REGEX)!=null}const d0=(n,e)=>{if(typeof fetch>"u"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(n)?t=n.every(s=>ad(s)):t=ad(n),t)return Vf(n,e)}return null};Xe.registerSaveRouter(d0);Xe.registerLoadRouter(d0);function Vf(n,e){return new Bf(n,e)}function p0(n,e){return Vf(n,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Th{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class f0{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class AR{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function RR(n,e,t,s){const r=arguments;return new AR(Wl(...r))}function Wl(n,e,t,s){return arguments.length===1?n.modelTopology!=null||n.weightSpecs!=null?new Th(n):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Th({modelTopology:n})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Th({modelTopology:n,weightSpecs:e,weightData:t,trainingConfig:s}))}function DR(n){return new f0(n)}function OR(n){return new f0(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const m0=Object.freeze(Object.defineProperty({__proto__:null,CompositeArrayBuffer:Kn,browserFiles:NR,browserHTTPRequest:p0,concatenateArrayBuffers:zx,copyModel:CN,decodeWeights:ef,decodeWeightsStream:Px,encodeWeights:Zh,fromMemory:RR,fromMemorySync:Wl,getLoadHandlers:Vx,getModelArtifactsForJSON:sf,getModelArtifactsForJSONSync:nf,getModelArtifactsInfoForJSON:Ei,getSaveHandlers:Bx,getWeightSpecs:Ml,http:Vf,isHTTPScheme:ad,listModels:IN,loadWeights:c0,moveModel:kN,registerLoadRouter:dN,registerSaveRouter:hN,removeModel:NN,weightsLoaderFactory:h0,withSaveHandler:DR,withSaveHandlerSync:OR},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _R(n,e,t){const s=N(n,"labels","confusionMatrix"),r=N(e,"predictions","confusionMatrix");I(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),I(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),I(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),I(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),I(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);const o=va(ee(s,"int32"),t),a=va(ee(r,"int32"),t),i=ke(o),l=Ne(i,a);return ee(l,"int32")}const FR=D({confusionMatrix_:_R});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OJ=Object.freeze(Object.defineProperty({__proto__:null,confusionMatrix:FR},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let br,Vy=!1;function g0(n,e=3){if(e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let t=!1,s=!1,r=!1,o=!1,a=!1,i=!1;if(n.data instanceof Uint8Array)t=!0;else if(typeof ImageData<"u"&&n instanceof ImageData)s=!0;else if(typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement)o=!0;else if(n.getContext!=null)a=!0;else if(typeof ImageBitmap<"u"&&n instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${n.constructor.name}`);if(Pl(Uh,R.backendName)!=null){const f={pixels:n},g={numChannels:e};return R.runKernel(Uh,f,g)}const[u,c]=r?[n.videoWidth,n.videoHeight]:[n.width,n.height];let h;if(a)h=n.getContext("2d").getImageData(0,0,u,c).data;else if(s||t)h=n.data;else if(o||r||i){if(br==null)if(typeof document>"u")if(typeof OffscreenCanvas<"u"&&typeof OffscreenCanvasRenderingContext2D<"u")br=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else br=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});br.canvas.width=u,br.canvas.height=c,br.drawImage(n,0,0,u,c),h=br.getImageData(0,0,u,c).data}let d;if(e===4)d=new Int32Array(h);else{const f=u*c;d=new Int32Array(f*e);for(let g=0;g4||e===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${e}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`)}function VR(n){const e=(n==null?void 0:n.alpha)||1;if(e>1||e<0)throw new Error(`Alpha value ${e} is suppoed to be in range [0 - 1].`)}async function WR(n,e){let t=N(n,"img","toPixels");if(!(n instanceof Re)){const u=t;t=ee(u,"int32"),u.dispose()}y0(t);const[s,r]=t.shape.slice(0,2),o=t.rank===2?1:t.shape[2],a=await t.data(),i=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${p}.`)}else if(t.dtype==="int32"&&(p<0||p>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${p}.`);o===1?(c[0]=p*i,c[1]=p*i,c[2]=p*i):c[d]=p*i}const h=u*4;l[h+0]=Math.round(c[0]),l[h+1]=Math.round(c[1]),l[h+2]=Math.round(c[2]),l[h+3]=Math.round(c[3])}if(e!=null){Vy||Pl(ip,R.backendName)!=null&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),Vy=!0),e.width=r,e.height=s;const u=e.getContext("2d"),c=new ImageData(l,r,s);u.putImageData(c,0,0)}return t!==n&&t.dispose(),l}function UR(n,e,t){let s=N(n,"img","draw");if(!(n instanceof Re)){const a=s;s=ee(a,"int32"),a.dispose()}y0(s),VR(t==null?void 0:t.imageOptions);const r={image:s},o={canvas:e,options:t};R.runKernel(ip,r,o)}const b0=D({fromPixels_:g0}),_J=Object.freeze(Object.defineProperty({__proto__:null,draw:UR,fromPixels:b0,fromPixelsAsync:BR,toPixels:WR},Symbol.toStringTag,{value:"Module"}));function Wc(n,e){const t=n.shape.length,s=e.shape.length;if(t<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if(e.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.shape[s-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[s-1]} vs. ${t}`);if(G(n.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);const r=e.shape,o=r[r.length-1];let a=1;for(let h=0;hh/u),1].slice(0,o);return[l,a,u,c]}const FJ=Object.freeze(Object.defineProperty({__proto__:null,prepareAndValidate:Wc},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const id=-2,GR=-1;function Wf(n,e,t){const s=n.shape.length;I(s===e.length,()=>`Error in slice${s}D: Length of begin ${e} must match the rank of the array (${s}).`),I(s===t.length,()=>`Error in slice${s}D: Length of size ${t} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${e[r]+t[r]}) would overflow input.shape[${r}] (${n.shape[r]})`)}function HR(n){const e=[];let t=0;for(;n>0;)n&1&&e.push(t),n/=2,t++;return e}function Uf(n,e,t){const s=[];for(let r=0;r0){const p=e[0],f=t+1;c=$0(a,p,f,s,n),h=S0(i,p,f,r,n),d=x0(o,p,f,n)}else for(let p=0;p-1)o[i]=0;else{const l=w0(e,t,i);let u=s[l];n&1<-1)o[i]=Number.MAX_SAFE_INTEGER;else{const l=w0(e,t,i);let u=s[l];n&1<0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const l=s[r];return a<0&&(a+=l),a=Ys(0,a,l-1),a}function C0(n,e,t,s,r,o){let a=e[r];const i=t[r]||1;(n&1<0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const l=s[r];return a<0&&(a+=l),i>0?a=Ys(0,a,l):a=Ys(-1,a,l-1),a}function Gf(n,e,t){let s=t.length;for(let r=0;r1){s=r;break}for(let r=s+1;r0||t[r]!==n[r])return!1;return!0}function Hf(n,e){let t=n.length>0?n[n.length-1]:1;for(let s=0;s{I(a!==-1,()=>"slice() does not support negative begin indexing.")});let o;return t==null?o=new Array(r).fill(-1):typeof t=="number"?o=[t,...new Array(r-1).fill(-1)]:t.lengtha>=0?a:(I(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`),n.shape[i]-s[i])),[s,o]}function jf(n,e,t,s,r,o,a,i,l){let u;if(s==null?(u=new Array(e.length),u.fill(1)):u=s,a!=null&&(a&a-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:u.length,numAddAxisAfterEllipsis:0,begin:e.slice(),end:t.slice(),strides:u.slice(),beginMask:r,endMask:o,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};for(let w=0;w0?0:-1,d.strides[w]>0?$:$-1];if(x&&d.strides[w]<=0)throw Error("only stride 1 allowed on non-range indexing.");g=g&&d.strides[w]===1;const A=!!(d.beginMask&1<=$)throw Error(`slice index ${d.begin[w]} of dimension ${w} out of bounds.`)}else d.begin[w]=Wy(d.begin[w],0,d.strides[w],$,C,E),d.end[w]=Wy(d.end[w],1,d.strides[w],$,C,E);const S=d.strides[w]===1&&d.begin[w]===0&&d.end[w]===$;p=p&&S,f=f&&(w===0&&d.strides[w]===1||S)}else p=p&&d.strides[w]===1&&A,f=f&&(w===0&&d.strides[w]===1||A);let k,T=!1;if(d.beginValid&&d.endValid?(k=d.end[w]-d.begin[w],T=!0):x?(k=1,T=!0):A&&$>=0&&(d.strides[w]<0?k=-$:k=$,T=!0),T){let S;k===0||k<0!=d.strides[w]<0?S=0:S=Math.trunc(k/d.strides[w])+(k%d.strides[w]!==0?1:0),m.push(S)}else m.push(-1)}for(let w=0;w=0?y.push(m[x]):x===id&&y.push(1)}return{finalShapeSparse:y.filter((w,x)=>d.finalShapeGatherIndices[x]!==id),finalShape:y,isIdentity:p,sliceDim0:f,isSimpleSlice:g,begin:d.begin,end:d.end,strides:d.strides}}function qR(n,e){e.beginMask=0,e.endMask=0,e.shrinkAxisMask=0;let t=0;e.beginValid=n.begin!=null,e.endValid=n.end!=null,e.begin=new Array(e.dims),e.end=new Array(e.dims),e.strides=new Array(e.dims),e.finalShapeGatherIndices=[],e.finalShapeGatherIndicesSparse=[],e.inputShapeGatherIndicesSparse=new Array(e.dims);for(let s=0;s0?o[e]:o[e+1&1];{const a=n<0?s+n:n;return ao[1]?o[1]:a}}const KR=Object.freeze(Object.defineProperty({__proto__:null,assertParamsValid:Wf,computeFlatOffset:Hf,computeOutShape:Uf,getNormalizedAxes:jR,isSliceContinous:Gf,maskToAxes:HR,parseSliceParams:Uc,sliceInfo:jf,startForAxis:N0,startIndicesWithElidedDims:$0,stopForAxis:C0,stopIndicesWithElidedDims:S0,stridesForAxis:I0,stridesWithElidedDims:x0},Symbol.toStringTag,{value:"Module"}));/** @license See the LICENSE file. */const XR="4.22.0";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class YR{static sgd(e){return new Mf(e)}static momentum(e,t,s=!1){return new i0(e,t,s)}static rmsprop(e,t=.9,s=0,r=null,o=!1){return new l0(e,t,s,r,o)}static adam(e=.001,t=.9,s=.999,r=null){return new o0(e,t,s,r)}static adadelta(e=.001,t=.95,s=null){return new s0(e,t,s)}static adamax(e=.002,t=.9,s=.999,r=null,o=0){return new a0(e,t,s,r,o)}static adagrad(e,t=.1){return new r0(e,t)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const io=YR;/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZR=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:n=>n();function k0(){return new Promise(n=>ZR(()=>n()))}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qf(n,e){const t=n[0].length;n.forEach((r,o)=>{I(r.length===t,()=>`Error in concat${t}D: rank of tensors[${o}] must be the same as the rank of the rest (${t})`)}),I(e>=0&&e`Error in concat${t}D: axis must be between 0 and ${t-1}.`);const s=n[0];n.forEach((r,o)=>{for(let a=0;a`Error in concat${t}D: Shape of tensors[${o}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${o}.`)})}function rs(n,e){const t=n[0].slice();for(let s=1;s=0)if(i>=0){if(i!==o)throw new Error(`rt input.shape and shape=${e} are incompatible: rt input.shape[${r+n}] = ${o} but shape[${r+n}] = ${i}`)}else s[a]=o}return s}function E0(n){const e={FIRST_DIM_SIZE:Mn.FIRST_DIM_SIZE,VALUE_ROWIDS:Mn.VALUE_ROWIDS,ROW_LENGTHS:Mn.ROW_LENGTHS,ROW_SPLITS:Mn.ROW_SPLITS,ROW_LIMITS:Mn.ROW_LIMITS,ROW_STARTS:Mn.ROW_STARTS},t=[];for(const s of n)if(s in e)t.push(e[s]);else break;return t}function A0(n){return n.length===0?0:n[0]===Mn.FIRST_DIM_SIZE?n.length-1:n.length}function R0(n,e){if(n==null||e==null)return;const t=n.length,s=e.length;if(t>=s)throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${e}, are incompatible: defaultValue.rank = ${t} must be less than ragged tensor input flatValues.rank = ${s})`);for(let r=0;r=0&&a>=0&&o!==1&&o!==a)throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${e} are incompatible: defaultValue.shape[${r-n.length}] = ${o} but ragged tensor input.flatValues.shape[${r-n.length}] = ${a}`)}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kf=30;function Gc(n){return n<=Kf?n:Ol(n,Math.floor(Math.sqrt(n)))}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xf(n,e,t){const s=t*(typeof n=="number"?n:n[0]),r=e*(typeof n=="number"?n:n[1]);return[s,r]}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pi(n,e,t,s=!0){let r=[];if(s)r=r.concat(e.slice(0)),r.push(n[0]/t),r=r.concat(n.slice(1));else{r=r.concat(n[0]);const o=e.length;for(let a=0;a=e*2+1||a%2===1?o.push(a):r.push(a);s.push(...r),s.push(0),s.push(...o)}return s}function Mi(n,e,t,s=!0){const r=[];s?r.push(n[0]/t):r.push(n[0]*t);for(let o=1;o/g,Uy=",",Gy="...";function om(n,e){n=n.replace(/\s/g,"");const t=(n.length-n.replace(JR,"").length)/Eh.length;if(t<1)throw new Error("Equations without an arrow are not supported.");if(t>1)throw new Error(`Equation must contain exactly one arrow ("${Eh}").`);const[s,r]=n.split(Eh);I(s.indexOf(Gy)===-1,()=>`The ellipsis notation ("${Gy}") is not supported yet.`);const o=s.split(Uy),a=o.length;if(e!==a)throw new Error(`Expected ${a} input tensors, received ${e}`);if(a>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const i=[];for(let d=0;df.indexOf(p)!==-1))throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);i.indexOf(p)===-1&&i.push(p)}for(let d=0;dr!==-1),{permutationIndices:t,expandDims:s}}function im(n,e,t){const s=new Array(n);for(let r=0;r`Expected dimension ${s[e[r][a]]} at axis ${a} of input shaped ${JSON.stringify(o)}, but got dimension ${o[a]}`)}}function lm(n,e){const t=n,s=[];let r=0;n.length===0&&t.push(-1),r=n.length+1;for(let a=0;ae===t)}function QR(n,e){const t=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(e).fill(n.shape[t]/e);else{const r=e.reduce((a,i)=>(i===-1&&(a+=1),a),0);I(r<=1,()=>"There should be only one negative value in split array.");const o=e.indexOf(-1);if(o!==-1){const a=e.reduce((i,l)=>l>0?i+l:i);e[o]=n.shape[t]-a}I(n.shape[t]===e.reduce((a,i)=>a+i),()=>"The sum of sizes must match the size of the axis dimension."),s=e}return s}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function z0(n){return`Received SparseTensor with denseShape[0] = 0 but + indices.shape[0] = ${n}`}function M0(n,e){return`indices(${n}, 0) is invalid: ${e} < 0`}function B0(n,e,t){return`indices(${n}, 0) is invalid: ${e} >= ${t}`}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function V0(n,e){return`only one output dimension may be -1, not both ${n} and ${e}`}function W0(n,e){return`size ${n} must be non-negative, not ${e}`}function U0(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function G0(n,e){const t=G(n),s=G(e);return`Input to reshape is a SparseTensor with ${t} + dense values, but the requested shape requires a multiple of ${s}. inputShape=${n} outputShape= ${e}`}function H0(n,e){const t=G(n),s=G(e);return`Input to reshape is a tensor with ${t} dense values, but the requested shape has ${s}. inputShape=${n} outputShape=${e}`}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ld(){return"segment ids must be >= 0"}function j0(){return"segment ids are not increasing"}function q0(n,e){return`Segment id ${n} out of range [0, ${e}), possibly because segmentIds input is not sorted.`}function K0(n,e,t){return`Bad: indices[${n}] == ${e} out of range [0, ${t})`}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X0(n,e){let t=!1,s;for(n<=Kf?(s=n,t=!0):s=Ol(n,Math.floor(Math.sqrt(n)));!t;)s>e||s===n?t=!0:s=Ol(n,s+1);return s}function Y0(n,e,t){const s=[],r=n.length;for(let o=0;or))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>o)throw new Error(`batchDims (${s}) must be less than rank(x) ( + ${o}).`);if(tSs(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Z0(n){return n.map(e=>ns(e))}const tD=Object.freeze(Object.defineProperty({__proto__:null,ERF_A1:Qf,ERF_A2:em,ERF_A3:tm,ERF_A4:nm,ERF_A5:sm,ERF_P:Jf,PARALLELIZE_THRESHOLD:Kf,get RowPartitionType(){return Mn},SELU_SCALE:jc,SELU_SCALEALPHA:Hc,applyActivation:Pc,assertAndGetBroadcastShape:ye,assertAxesAreInnerMostDims:Ot,assertParamsConsistent:qf,assignToTypedArray:F0,axesAreInnerMostDims:ff,calculateShapes:pr,checkEinsumDimSizes:im,checkPadOnDimRoundingMode:Gt,combineLocations:vw,combineRaggedTensorToTensorShapes:T0,complexWithEvenIndex:O0,complexWithOddIndex:_0,computeConv2DInfo:$t,computeConv3DInfo:ur,computeDefaultPad:af,computeDilation2DInfo:Ai,computeOptimalWindowSize:Gc,computeOutAndReduceShapes:St,computeOutShape:rs,computePool2DInfo:Dn,computePool3DInfo:Rs,convertConv2DDataFormat:Ds,decodeEinsumEquation:om,eitherStridesOrDilationsAreOne:Dt,expandShapeToKeepDim:nt,exponent:P0,exponents:L0,fromStringArrayToUint8:Z0,fromUint8ToStringArray:Ts,getAxesPermutation:Je,getBroadcastDims:Pr,getComplexWithIndex:rm,getEinsumComputePath:lm,getEinsumPermutation:am,getFusedBiasGradient:Lc,getFusedDyActivation:Fc,getImageCenter:Xf,getInnerMostAxes:st,getPermuted:zi,getRaggedRank:A0,getReductionAxes:it,getReshaped:Pi,getReshapedPermuted:Mi,getRowPartitionTypesHelper:E0,getSliceBeginCoords:Yf,getSliceSize:Zf,getSparseFillEmptyRowsIndicesDenseShapeMismatch:z0,getSparseFillEmptyRowsNegativeIndexErrorMessage:M0,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:B0,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:U0,getSparseReshapeInputOutputMismatchErrorMessage:H0,getSparseReshapeInputOutputMultipleErrorMessage:G0,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:V0,getSparseReshapeNegativeOutputDimErrorMessage:W0,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:K0,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:ld,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:j0,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:q0,getUndoAxesPermutation:cr,isIdentityPermutation:um,log:kI,mergeRealAndImagArrays:ks,prepareAndValidate:Wc,prepareSplitSize:cm,segment_util:eD,shouldFuse:zc,slice_util:KR,splitRealAndImagArrays:D0,stridesOrDilationsArePositive:Fr,tupleValuesAreOne:er,upcastType:an,validateDefaultValueShape:R0,validateInput:Oc,validateUpdateShape:Of,warn:fn},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LJ=Object.freeze(Object.defineProperty({__proto__:null,nonMaxSuppressionV3Impl:Mc,nonMaxSuppressionV4Impl:Bc,nonMaxSuppressionV5Impl:Vc,whereImpl:_c},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */bR();/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const J0={kernelName:hu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,Fo(ee(t,"float32"),-1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nD={kernelName:Oa,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=ze(ee(t,"float32")),r=At(ae(pe(1),s));return Ge(ce(n,r))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sD={kernelName:_a,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=At(ae(ze(ee(t,"float32")),1));return ce(n,s)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rD={kernelName:Ro,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{let i=n;const l=it(t.shape,r);return l.length>0&&(i=ie(i,l)),F(i,t.shape)},b:()=>{let i=n;const l=it(s.shape,r);return l.length>0&&(i=ie(i,l)),F(i,s.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oD={kernelName:du,saveAllInputs:!0,gradFunc:(n,e)=>{const t={};return e.forEach((s,r)=>{t[r]=()=>n.clone()}),t}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aD={kernelName:pu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Ee(t)}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iD={kernelName:fu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Ee(t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lD={kernelName:Fa,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,At(ae(pe(1),ze(ee(t,"float32")))))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uD={kernelName:La,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=At(Y(pe(1),ze(ee(t,"float32"))));return ce(n,s)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cD={kernelName:Ma,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{const i=Y(ze(t),ze(s));let l=O(n,ce(s,i));const u=it(t.shape,r);return u.length>0&&(l=ie(l,u)),F(l,t.shape)},b:()=>{const i=Y(ze(t),ze(s));let l=Ge(O(n,ce(t,i)));const u=it(s.shape,r);return u.length>0&&(l=ie(l,u)),F(l,s.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hD={kernelName:Pa,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,Y(ze(ee(t,"float32")),1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dD={kernelName:za,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,ae(pe(1),ze(ee(t,"float32"))))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pD(n,e,t,s,r,o){const a=N(n,"dy","avgPool3dGrad"),i=N(e,"input","avgPool3dGrad");let l=a,u=i,c=!1;i.rank===4&&(c=!0,l=F(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),u=F(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),I(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),I(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),Gt("avgPool3dGrad",r,o);const h={dy:l,input:u},d={filterSize:t,strides:s,pad:r,dimRoundingMode:o},p=R.runKernel(qd,h,d);return c?F(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}const fD=D({avgPool3dGrad_:pD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mD={kernelName:gu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{filterSize:r,strides:o,pad:a,dimRoundingMode:i}=t;return{x:()=>fD(n,s,r,o,a,i)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gD(n,e,t,s,r){const o=N(n,"dy","avgPoolGrad"),a=N(e,"input","avgPoolGrad");I(a.rank===o.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${o.rank})`);let i=a,l=o,u=!1;a.rank===3&&(u=!0,i=F(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=F(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),I(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);const c={dy:l,input:i},h={filterSize:t,strides:s,pad:r},d=R.runKernel(jd,c,h);return u?F(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const yD=D({avgPoolGrad_:gD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bD={kernelName:mu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{filterSize:r,strides:o,pad:a}=t;return{x:()=>yD(n,s,r,o,a)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xD={kernelName:yu,inputsToSave:["a","b"],gradFunc:(n,e,t)=>{const[s,r]=e,{transposeA:o,transposeB:a}=t;return!o&&!a?{a:()=>Ne(n,r,!1,!0),b:()=>Ne(s,n,!0,!1)}:!o&&a?{a:()=>Ne(n,r,!1,!1),b:()=>Ne(n,s,!0,!1)}:o&&!a?{a:()=>Ne(r,n,!1,!0),b:()=>Ne(s,n,!1,!1)}:{a:()=>Ne(r,n,!0,!0),b:()=>Ne(n,s,!0,!0)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wD={kernelName:bu,gradFunc:(n,e,t)=>{const{blockShape:s,crops:r}=t;return{x:()=>Cc(n,s,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vD={kernelName:NI,gradFunc:(n,e,t)=>{const s=t,r=s.inputShape,o=s.shape,a=Array.from(o);for(let l=r.length-1;l>=0;l--)if(r[l]===o[l])a[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${o}].`);const i=[];for(let l=0;l1&&i.push(l);return{x:()=>ie(n,i,!0)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $D={kernelName:Ba,gradFunc:n=>({x:()=>n.clone()})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SD={kernelName:Va,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ID={kernelName:Wa,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{clipValueMin:r,clipValueMax:o}=t;return{x:()=>Tt(Gn(hr(s,r),Yr(s,o)),n,Ee(n))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ND={kernelName:wu,inputsToSave:["x"],gradFunc:J0.gradFunc};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CD={kernelName:vu,saveAllInputs:!0,gradFunc:(n,e,t)=>{const s=e.map(l=>l.shape),{axis:r}=t,o=Se(r,e[0].shape)[0],a=s.map(l=>l[o]);return on(n,a,o).map(l=>()=>l)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kD={kernelName:$u,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const[s,r]=e,{dilations:o,strides:a,pad:i,dataFormat:l}=t;return I(er(o),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`),{x:()=>uf(s.shape,n,r,a,i,l),filter:()=>Pf(s,n,r.shape,a,i,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TD={kernelName:Su,inputsToSave:["dy","filter"],gradFunc:(n,e,t)=>{const[s,r]=e,{strides:o,pad:a,dataFormat:i,dimRoundingMode:l}=t;return{dy:()=>tr(n,r,o,a,i,1,l),filter:()=>Pf(n,s,r.shape,o,a,i,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ED(n,e,t,s,r){let o=n;n.rank===4&&(o=F(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));let a=e;a.rank===4&&(a=F(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),I(o.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${o.shape}.`),I(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),I(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),I(o.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${o.shape[4]}) must match input depth in filter (${t[3]}.`),I(a.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${t[4]}).`);const i={x:o,dy:a},l={strides:s,pad:r,filterShape:t};return R.runKernel(Jd,i,l)}const AD=D({conv3DBackpropFilter_:ED});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RD={kernelName:Iu,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const{dilations:s,strides:r,pad:o}=t;I(er(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[a,i]=e;return{x:()=>mw(a.shape,n,i,r,o),filter:()=>AD(a,n,i.shape,r,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DD={kernelName:Ua,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(Ge(Tf(ee(t,"float32"))),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OD={kernelName:Ga,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(Ef(ee(t,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _D={kernelName:Nu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{axis:r,exclusive:o,reverse:a}=t;return{x:()=>{const i=Je([r],s.rank);let l=df(n,r,o,!a);return i!=null&&(l=ke(l,i)),l}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FD={kernelName:Cu,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const{dilations:s,strides:r,pad:o,dimRoundingMode:a}=t,i=s??[1,1];I(er(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);const[l,u]=e;return I(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),I(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),I(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),I(Dt(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),Gt("depthwiseConv2d",o,a),{x:()=>Zw(l.shape,n,u,r,o,i,a),filter:()=>Yw(l,n,u.shape,r,o,i,a)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LD={kernelName:ku,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const[s,r]=e,o={x:s,filter:r,dy:n},a={x:s,filter:r,dy:n};return{x:()=>R.runKernel(Vh,o,t),filter:()=>R.runKernel(Wh,a,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PD={kernelName:ja,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e,s={dy:n,y:t};return{x:()=>R.runKernel(up,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zD={kernelName:qa,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e,s=O(un(Ge(ze(t))),2/Math.sqrt(Math.PI));return{x:()=>O(n,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MD={kernelName:Ka,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BD={kernelName:Eu,inputsToSave:["input"],gradFunc:(n,e)=>{const[t]=e;return{input:()=>F(n,t.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VD={kernelName:Xa,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,un(t))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WD={kernelName:Ya,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UD={kernelName:Za,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{const i=ce(n,ee(s,"float32")),l=it(t.shape,r);return l.length>0?F(ie(i,l),t.shape):i},b:()=>{let i=O(n,ee(t,"float32"));const l=it(s.shape,r);l.length>0&&(i=F(ie(i,l),s.shape));const u=ze(s);return Ge(ce(i,ee(u,"float32")))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GD={kernelName:Au,inputsToSave:["x","mean","variance","scale"],gradFunc:(n,e,t)=>{const{varianceEpsilon:s}=t,[r,o,a,i]=e,l=i??pe(1),u=it(o.shape,r.shape),c=[];if(o.rank===1){for(let x=0;xo.rank===1?F(O(O(n,kn(F(p,[1,1,1,o.shape[0]]),c)),l),r.shape):F(O(O(n,p),l),r.shape),mean:()=>{let x=O(O(p,pe(-1)),d);return o.rank===1&&(x=ie(x,u)),F(x,o.shape)},variance:()=>{let x=O(O(f,h),d);return o.rank===1&&(x=ie(x,u)),F(x,o.shape)},scale:()=>{const x=O(h,p);let $=O(n,x);return o.rank===1&&($=ie($,u)),F($,o.shape)},offset:()=>{let x=n;return o.rank===1&&(x=ie(x,u)),F(x,o.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HD={kernelName:Ru,inputsToSave:["x","indices"],gradFunc:(n,e,t)=>{const[s,r]=e,{axis:o,batchDims:a}=t,i=Se(o,s.shape)[0],l=(u,c,h)=>()=>{const d=u.shape,p=c.size,f=d.slice(0,i),g=f.length,m=d.slice(o,d.length).slice(1),y=m.length,b=Hy(0,g),w=Hy(g+1,g+1+y),x=jy([f,[p],m]),$=F(h,x),C=F(c,[p]),E=jy([[g],b,w]),A=ke($,E);let k=Ff(A,C,u.shape[i]);const T=cr(E);return k=ke(k,T),k};if(a===1){const u=s.shape[0],c=s.split(u,0);return{x:()=>Xt(c.map((p,f)=>l(p,r.slice(f,1),n.slice(f,1))())).reshape(s.shape),indices:()=>r}}else return{x:l(s,r,n),indices:()=>r}}};function Hy(n,e){const t=[];for(let s=n;s{const[t,s]=e;return{a:()=>Ee(t),b:()=>Ee(s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qD={kernelName:Qa,gradFunc:n=>({x:()=>ee(n,"float32")})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KD={kernelName:ei,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const XD={kernelName:ti,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YD={kernelName:ni,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZD={kernelName:Ou,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{alpha:r}=t,o=Jt(s,0);return{x:()=>Tt(o,n,O(n,r))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JD={kernelName:ri,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,Y(t,1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QD={kernelName:si,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,ee(t,"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eO={kernelName:CI,inputsToSave:[],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s]=e,{axis:r}=t;return{logits:()=>{const a=un(s);return ae(n,O(ie(n,r,!0),a))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tO(n,e,t,s=5,r=1,o=1,a=.5){const i={x:n,y:e,dy:t},l={depthRadius:s,bias:r,alpha:o,beta:a};return R.runKernel(yp,i,l)}const nO=D({localResponseNormalizationBackprop_:tO});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sO={kernelName:Mu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s,r]=e,{depthRadius:o,bias:a,alpha:i,beta:l}=t;return{x:()=>nO(s,r,n,o,a,i,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Q0(n,e,t,s){return e.rankO(n,ee(wn(t,e),n.dtype))}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qy={kernelName:Bu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const s=t,{reductionIndices:r}=s,o=e[0],a=e[1],i=Se(r,o.shape),l=Q0(n,a,o,i);return{x:()=>l.x()}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rO={kernelName:oi,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e;return{a:()=>O(n,ee(hr(t,s),"float32")),b:()=>O(n,ee(wa(t,s),"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oO(n,e,t,s,r,o,a){const i=N(n,"dy","maxPool3dGrad"),l=N(e,"input","maxPool3dGrad"),u=N(t,"output","maxPool3dGrad");let c=i,h=l,d=u,p=!1;l.rank===4&&(p=!0,c=F(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),h=F(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=F(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),I(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),I(h.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),I(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),Gt("maxPool3dGrad",o,a);const f={dy:c,input:h,output:d},g={filterSize:s,strides:r,pad:o,dimRoundingMode:a},m=R.runKernel(xp,f,g);return p?F(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}const aO=D({maxPool3dGrad_:oO});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iO={kernelName:Wu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s,r]=e,{filterSize:o,strides:a,pad:i,dimRoundingMode:l}=t;return{x:()=>aO(n,s,r,o,a,i,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lO(n,e,t,s,r,o,a){const i=N(n,"dy","maxPoolGrad"),l=N(e,"input","maxPoolGrad"),u=N(t,"output","maxPoolGrad");I(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),I(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),I(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Gt("maxPoolGrad",o,a);const c={dy:i,input:l,output:u},h={filterSize:s,strides:r,pad:o,dimRoundingMode:a};return R.runKernel(bp,c,h)}const uO=D({maxPoolGrad_:lO});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cO={kernelName:Vu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s,r]=e,{filterSize:o,strides:a,pad:i}=t;return{x:()=>uO(n,s,r,o,a,i)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hO={kernelName:Uu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{axis:r}=t,o=Se(r,s.shape),i=St(s.shape,o)[1],l=G(i);return{x:()=>{const c=s.shape.slice();o.forEach(p=>{c[p]=1});const h=F(n,c);return ce(O(h,rn(s.shape,"float32")),l)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dO={kernelName:Gu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const s=t,{axis:r}=s,[o,a]=e,i=Se(r,o.shape),l=Q0(n,a,o,i);return{x:()=>l.x()}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pO={kernelName:ai,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e;return{a:()=>O(n,ee(Yr(t,s),"float32")),b:()=>O(n,ee(Jt(t,s),"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fO={kernelName:Hu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const s=e[0],{paddings:r}=t,o=r.map(a=>a[0]);return{x:()=>Te(n,o,s.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mO={kernelName:ii,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{const i=it(t.shape,r);return i.length>0?F(ie(n,i),t.shape):n},b:()=>{const i=O(n,Ge(Fi(ce(t,s)))),l=it(s.shape,r);return l.length>0?F(ie(i,l),s.shape):i}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gO={kernelName:li,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{const i=O(n,ee(s,"float32")),l=it(t.shape,r);return l.length>0?F(ie(i,l),t.shape):i},b:()=>{const i=O(n,ee(t,"float32")),l=it(s.shape,r);return l.length>0?F(ie(i,l),s.shape):i}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yO={kernelName:ju,gradFunc:n=>({x:()=>Ge(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bO={kernelName:Xu,inputsToSave:["indices"],gradFunc:(n,e)=>{const t=e[0];return{indices:()=>ct(t.shape,"float32")}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xO={kernelName:Ku,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wO={kernelName:Yu,saveAllInputs:!0,gradFunc:(n,e,t)=>{const{axis:s}=t;return Rn(n,s).map(o=>()=>o)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ky={kernelName:Zu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const s=e[0],{paddings:r}=t,o=r.map(a=>a[0]);return{x:()=>Te(n,o,s.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vO={kernelName:ui,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(n,e)=>{const[t,s,r]=e,o=t,a=s,i=ye(o.shape,a.shape);return{a:()=>{const c=ee(a,"float32");let h=O(n,O(c,Ns(o,ae(c,pe(1)))));const d=it(o.shape,i);return d.length>0&&(h=ie(h,d)),F(h,o.shape)},b:()=>{const c=Jt(o,0),h=Tt(c,vn(o),Ee(o));let d=O(n,O(r,h));const p=it(a.shape,i);return p.length>0&&(d=ie(d,p)),F(d,a.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $O={kernelName:Ju,inputsToSave:["x","alpha"],gradFunc:(n,e)=>{const[t,s]=e,r=Jt(t,0);return{x:()=>Tt(r,n,O(n,s)),alpha:()=>{let o=Tt(r,Ee(n),O(n,t));const a=it(s.shape,n.shape);return a.length>0&&(o=ie(o,a)),F(o,s.shape)}}}};/** + * @license + * Copyright 2022 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SO(n,e,t){const s=n.shape.slice();s[t]=1;const r=F(e,s),o=Vl(n,t,!0,!1),a=Vl(n,t,!0,!0),i=O(o,a);return O(r,i)}function IO(n,e,t){const s=n.shape.length,r=s-t.length,o=Je(t,s);let a=n;o!=null&&(a=ke(n,o));const i=a.shape.slice(),u=i.splice(s-t.length,t.length).reduce((d,p)=>d*p,1);i.push(u);const c=a.reshape(i);let h=SO(c,e,r);if(h=h.reshape(a.shape),o!=null){const d=cr(o);h=ke(h,d)}return h}const NO={kernelName:Qu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{axis:r}=t;let o=[];return r==null?o=s.shape.map((a,i)=>i):typeof r=="number"?o=[r]:o=r,{x:()=>IO(s,n,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CO={kernelName:Ha,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{const i=ce(n,ee(s,"float32")),l=it(t.shape,r);return l.length>0?F(ie(i,l),t.shape):i},b:()=>{let i=O(n,ee(t,"float32"));const l=it(s.shape,r);l.length>0&&(i=F(ie(i,l),s.shape));const u=ze(s);return Ge(ce(i,ee(u,"float32")))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kO={kernelName:ci,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,Ge(ze(t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TO={kernelName:di,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e,s=O(Yr(t,6),Fo(t));return{x:()=>O(n,ee(s,"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EO={kernelName:hi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,ee(Fo(t),"float32"))}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const AO={kernelName:ec,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>F(n,t.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RO={kernelName:nc,inputsToSave:["images"],gradFunc:(n,e,t)=>{const[s]=e,r={dy:n,images:s};return{images:()=>R.runKernel(Rp,r,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DO={kernelName:tc,inputsToSave:["images"],gradFunc:(n,e,t)=>{const[s]=e,r={dy:n,images:s};return{images:()=>R.runKernel(Ap,r,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OO={kernelName:sc,gradFunc:(n,e,t)=>{const{dims:s}=t,r=Se(s,n.shape);return{x:()=>An(n,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _O={kernelName:pi,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FO={kernelName:fi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Ge(ce(n,O(Ns(t,1.5),2)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LO={kernelName:rc,inputsToSave:["condition"],gradFunc:(n,e)=>{const[t]=e;return{condition:()=>ee(Ee(t),"float32"),t:()=>O(n,ee(t,n.dtype)),e:()=>O(n,ee(Sc(t),n.dtype))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PO={kernelName:mi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=Jt(t,pe(0)),r=pe(Hc),o=pe(jc),a=O(n,o),i=O(O(n,r),un(ee(t,"float32")));return Tt(s,a,i)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zO={kernelName:xi,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,O(t,ae(pe(1),t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MO={kernelName:bi,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BO={kernelName:gi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(yc(ee(t,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VO={kernelName:yi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(hf(ee(t,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WO={kernelName:oc,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{begin:r,size:o}=t,a=s.shape,[i,l]=Uc(s,r,o),u=[];for(let c=0;cdr(n,u)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UO={kernelName:uc,outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s]=e,{dim:r}=t,o=!0,a=O(n,s);return{logits:()=>ae(a,O(ie(a,[r],o),s))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GO={kernelName:wi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,ss(t))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xy={kernelName:ic,gradFunc:(n,e,t)=>{const{blockShape:s,paddings:r}=t;return{x:()=>gc(n,s,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yy={kernelName:lc,gradFunc:(n,e,t)=>{const{axis:s}=t;return{x:()=>at(n,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HO={kernelName:vi,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,O(At(ee(t,"float32")),2))}}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jO={kernelName:Bp,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(n,O(ee(t,"float32"),2))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qO={kernelName:$i,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pe(2);return{a:()=>O(n,O(r,ae(t,s))),b:()=>O(n,O(r,ae(s,t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KO={kernelName:ki,gradFunc:n=>({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const XO={kernelName:Si,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=ye(t.shape,s.shape);return{a:()=>{let i=n;const l=it(t.shape,r);return l.length>0&&(i=ie(i,l)),F(i,t.shape)},b:()=>{let i=n;const l=it(s.shape,r);return l.length>0&&(i=ie(i,l)),F(Ge(i),s.shape)}}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YO={kernelName:ac,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,r=s.shape.slice(),{axis:o}=t;Se(o,s.shape).forEach(u=>{r[u]=1});const i=F(n,r),l=O(i,rn(s.shape,"float32"));return{x:()=>l}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZO={kernelName:Ii,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ce(n,ze(yc(t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JO={kernelName:Ni,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>O(ae(pe(1),ze(t)),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QO={kernelName:Ci,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{reps:r}=t;return{x:()=>{let a=Ee(s);if(s.rank===1)for(let i=0;i{const s=t,{perm:r}=s,o=cr(r);return{x:()=>ke(n,o)}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const t_={kernelName:hc,gradFunc:(n,e,t)=>{const s=t,{axis:r}=s;return{value:()=>Xt(n,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n_={kernelName:dc,inputsToSave:["segmentIds"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>s_(n,t)}}};function s_(n,e){const t=Os(e,Ee(e)),s=Li(n,t);let r=hr(e,pe(0,"int32"));const o=s.rank-r.rank;for(let i=0;i({x:()=>Ee(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const o_=[J0,nD,sD,rD,oD,aD,iD,lD,uD,cD,hD,dD,mD,bD,xD,wD,vD,$D,SD,ID,ND,CD,TD,kD,RD,DD,OD,_D,FD,LD,CO,PD,zD,MD,BD,VD,UD,WD,GD,HD,jD,qD,KD,XD,YD,ZD,JD,QD,eO,sO,qy,qy,rO,iO,cO,hO,dO,pO,fO,mO,gO,yO,bO,xO,wO,Ky,Ky,vO,$O,NO,kO,TO,EO,AO,RO,DO,OO,_O,FO,LO,PO,zO,MO,BO,VO,WO,UO,GO,Xy,Xy,Yy,Yy,HO,qO,jO,KO,XO,YO,ZO,JO,QO,e_,t_,n_,r_];for(const n of o_)TI(n);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.abs=function(){return this.throwIfDisposed(),lt(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.acos=function(){return this.throwIfDisposed(),Yx(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.acosh=function(){return this.throwIfDisposed(),Zx(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.add=function(n){return this.throwIfDisposed(),Y(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.all=function(n,e){return this.throwIfDisposed(),of(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.any=function(n,e){return this.throwIfDisposed(),Bl(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.argMax=function(n){return this.throwIfDisposed(),vo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.argMin=function(n){return this.throwIfDisposed(),Jx(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.asScalar=function(){return this.throwIfDisposed(),I(this.size===1,()=>"The array must have only 1 element."),F(this,[])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.asType=function(n){return this.throwIfDisposed(),ee(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.as1D=function(){return this.throwIfDisposed(),F(this,[this.size])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.as2D=function(n,e){return this.throwIfDisposed(),F(this,[n,e])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.as3D=function(n,e,t){return this.throwIfDisposed(),F(this,[n,e,t])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.as4D=function(n,e,t,s){return this.throwIfDisposed(),F(this,[n,e,t,s])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.as5D=function(n,e,t,s,r){return this.throwIfDisposed(),F(this,[n,e,t,s,r])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.asin=function(){return this.throwIfDisposed(),Qx(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.asinh=function(){return this.throwIfDisposed(),ew(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.atan=function(){return this.throwIfDisposed(),tw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.atan2=function(n){return this.throwIfDisposed(),nw(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.atanh=function(){return this.throwIfDisposed(),sw(this)};H().prototype.avgPool=function(n,e,t,s){return this.throwIfDisposed(),mc(this,n,e,t,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.batchToSpaceND=function(n,e){return this.throwIfDisposed(),gc(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.batchNorm=function(n,e,t,s,r){return this.throwIfDisposed(),Ri(this,n,e,t,s,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.broadcastTo=function(n){return this.throwIfDisposed(),yo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.cast=function(n){return this.throwIfDisposed(),ee(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.ceil=function(){return this.throwIfDisposed(),uw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.clipByValue=function(n,e){return this.throwIfDisposed(),ln(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.concat=function(n,e){return this.throwIfDisposed(),n instanceof Re&&(n=[n]),at([this,...n],e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.conv1d=function(n,e,t,s,r,o){return this.throwIfDisposed(),lf(this,n,e,t,s,r,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.conv2dTranspose=function(n,e,t,s,r){return this.throwIfDisposed(),cf(this,n,e,t,s,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.conv2d=function(n,e,t,s,r,o){return this.throwIfDisposed(),tr(this,n,e,t,s,r,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.cos=function(){return this.throwIfDisposed(),yc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.cosh=function(){return this.throwIfDisposed(),hf(this)};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.cumprod=function(n,e,t){return this.throwIfDisposed(),Vl(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.cumsum=function(n,e,t){return this.throwIfDisposed(),df(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.depthToSpace=function(n,e){return this.throwIfDisposed(),yw(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.depthwiseConv2d=function(n,e,t,s,r,o){return this.throwIfDisposed(),Di(this,n,e,t,s,r,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.dilation2d=function(n,e,t,s,r){return this.throwIfDisposed(),bw(this,n,e,t,s,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.divNoNan=function(n){return this.throwIfDisposed(),xw(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.div=function(n){return this.throwIfDisposed(),ce(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.dot=function(n){return this.throwIfDisposed(),ww(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.elu=function(){return this.throwIfDisposed(),Oi(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.equal=function(n){return this.throwIfDisposed(),wn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.erf=function(){return this.throwIfDisposed(),pf(this)};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.euclideanNorm=function(n,e){return this.throwIfDisposed(),Sw(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.exp=function(){return this.throwIfDisposed(),un(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.expandDims=function(n){return this.throwIfDisposed(),Lt(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.expm1=function(){return this.throwIfDisposed(),Iw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.fft=function(){return this.throwIfDisposed(),Rc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.flatten=function(){return this.throwIfDisposed(),F(this,[this.size])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.floor=function(){return this.throwIfDisposed(),Fi(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.floorDiv=function(n){return this.throwIfDisposed(),rf(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.gather=function(n,e,t){return this.throwIfDisposed(),Li(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.greaterEqual=function(n){return this.throwIfDisposed(),hr(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.greater=function(n){return this.throwIfDisposed(),Jt(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.ifft=function(){return this.throwIfDisposed(),Ia(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.irfft=function(){return this.throwIfDisposed(),Rf(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.isFinite=function(){return this.throwIfDisposed(),Nw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.isInf=function(){return this.throwIfDisposed(),Cw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.isNaN=function(){return this.throwIfDisposed(),kw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.leakyRelu=function(n){return this.throwIfDisposed(),xc(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.lessEqual=function(n){return this.throwIfDisposed(),Yr(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.less=function(n){return this.throwIfDisposed(),wa(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.localResponseNormalization=function(n,e,t,s){return this.throwIfDisposed(),Tw(this,n,e,t,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logSigmoid=function(){return this.throwIfDisposed(),Ew(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logSoftmax=function(n){return this.throwIfDisposed(),gf(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logSumExp=function(n,e){return this.throwIfDisposed(),$c(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.log=function(){return this.throwIfDisposed(),vn(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.log1p=function(){return this.throwIfDisposed(),wc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logicalAnd=function(n){return this.throwIfDisposed(),Gn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logicalNot=function(){return this.throwIfDisposed(),Sc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logicalOr=function(n){return this.throwIfDisposed(),yf(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.logicalXor=function(n){return this.throwIfDisposed(),Aw(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.matMul=function(n,e,t){return this.throwIfDisposed(),Ne(this,n,e,t)};H().prototype.maxPool=function(n,e,t,s){return this.throwIfDisposed(),Ic(this,n,e,t,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.max=function(n,e){return this.throwIfDisposed(),En(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.maximum=function(n){return this.throwIfDisposed(),Os(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.mean=function(n,e){return this.throwIfDisposed(),et(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.min=function(n,e){return this.throwIfDisposed(),xa(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.minimum=function(n){return this.throwIfDisposed(),zr(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.mirrorPad=function(n,e){return this.throwIfDisposed(),Dw(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.mod=function(n){return this.throwIfDisposed(),Ow(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.mul=function(n){return this.throwIfDisposed(),O(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.neg=function(){return this.throwIfDisposed(),Ge(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.norm=function(n,e,t){return this.throwIfDisposed(),_i(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.notEqual=function(n){return this.throwIfDisposed(),$o(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.oneHot=function(n,e=1,t=0){return this.throwIfDisposed(),va(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.onesLike=function(){return this.throwIfDisposed(),$n(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.pad=function(n,e){return this.throwIfDisposed(),dr(this,n,e)};H().prototype.pool=function(n,e,t,s,r,o){return this.throwIfDisposed(),_w(this,n,e,t,s,r,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.pow=function(n){return this.throwIfDisposed(),Ns(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.prelu=function(n){return this.throwIfDisposed(),kc(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.prod=function(n,e){return this.throwIfDisposed(),Fw(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.reciprocal=function(){return this.throwIfDisposed(),zw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.relu=function(){return this.throwIfDisposed(),hs(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.relu6=function(){return this.throwIfDisposed(),Sf(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.reshapeAs=function(n){return this.throwIfDisposed(),F(this,n.shape)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.reshape=function(n){return this.throwIfDisposed(),F(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.resizeBilinear=function(n,e,t){return this.throwIfDisposed(),e0(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.resizeNearestNeighbor=function(n,e,t){return this.throwIfDisposed(),t0(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.reverse=function(n){return this.throwIfDisposed(),An(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.rfft=function(){return this.throwIfDisposed(),Dc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.round=function(){return this.throwIfDisposed(),If(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.rsqrt=function(){return this.throwIfDisposed(),Nf(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.selu=function(){return this.throwIfDisposed(),Cf(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.separableConv2d=function(n,e,t,s,r,o){return this.throwIfDisposed(),kf(this,n,e,t,s,r,o)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sigmoid=function(){return this.throwIfDisposed(),ss(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sign=function(){return this.throwIfDisposed(),Mw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sin=function(){return this.throwIfDisposed(),Tf(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sinh=function(){return this.throwIfDisposed(),Ef(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.slice=function(n,e){return this.throwIfDisposed(),Te(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.softmax=function(n){return this.throwIfDisposed(),Ac(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.softplus=function(){return this.throwIfDisposed(),Oo(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.spaceToBatchND=function(n,e){return this.throwIfDisposed(),Cc(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.split=function(n,e){return this.throwIfDisposed(),on(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sqrt=function(){return this.throwIfDisposed(),At(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.square=function(){return this.throwIfDisposed(),ze(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.squaredDifference=function(n){return this.throwIfDisposed(),Df(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.squeeze=function(n){return this.throwIfDisposed(),Jr(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.stack=function(n,e){this.throwIfDisposed();const t=n instanceof Re?[this,n]:[this,...n];return Xt(t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.step=function(n){return this.throwIfDisposed(),Fo(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.stridedSlice=function(n,e,t,s,r,o,a,i){return this.throwIfDisposed(),Bw(this,n,e,t,s,r,o,a,i)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sub=function(n){return this.throwIfDisposed(),ae(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.sum=function(n,e){return this.throwIfDisposed(),ie(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.tan=function(){return this.throwIfDisposed(),Vw(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.tanh=function(){return this.throwIfDisposed(),Lr(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.tile=function(n){return this.throwIfDisposed(),kn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.toBool=function(){return this.throwIfDisposed(),ee(this,"bool")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.toFloat=function(){return this.throwIfDisposed(),ee(this,"float32")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.toInt=function(){return this.throwIfDisposed(),ee(this,"int32")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.topk=function(n,e){return this.throwIfDisposed(),Uw(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.transpose=function(n){return this.throwIfDisposed(),ke(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.unique=function(n){return this.throwIfDisposed(),Gw(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.unsortedSegmentSum=function(n,e){return this.throwIfDisposed(),Ff(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.unstack=function(n){return this.throwIfDisposed(),Rn(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.where=function(n,e){return this.throwIfDisposed(),Tt(n,this,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */H().prototype.zerosLike=function(){return this.throwIfDisposed(),Ee(this)};/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Zn extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Zn.prototype)}}class Tn extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Tn.prototype)}}class L extends Error{constructor(e){super(e),Object.setPrototypeOf(this,L.prototype)}}class xe extends Error{constructor(e){super(e),Object.setPrototypeOf(this,xe.prototype)}}class dm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,dm.prototype)}}/** + * @license + * Copyright 2022 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class e1{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const s=this.cache.keys().next().value;this.cache.delete(s)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;tt.toUpperCase())}let In={};function pm(n){if(n==null)return null;const e={};return e.className=n.getClassName(),e.config=n.getConfig(),e}function ud(n){if(!(n==null||typeof n!="object"))if(Array.isArray(n))n.forEach(e=>ud(e));else{const e=Object.keys(n);for(const t of e){const s=n[t];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?n[t]=s.value:ud(s))}}}function Bi(n,e={},t={},s="object",r=!1){if(typeof n=="string"){const o=n;let a;if(o in t)a=t[o];else if(o in In)a=In[o];else if(a=e[o],a==null)throw new L(`Unknown ${s}: ${n}. This may be due to one of the following reasons: +1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}else{const o=n;if(o.className==null||o.config==null)throw new L(`${s}: Improper config format: ${JSON.stringify(o)}. +'className' and 'config' must set.`);const a=o.className;let i,l;if(a in t?[i,l]=t[a]:a in In?[i,l]=In.className:a in e&&([i,l]=e[a]),i==null)throw new L(`Unknown ${s}: ${a}. This may be due to one of the following reasons: +1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){const u={};for(const p of Object.keys(In))u[p]=In[p];for(const p of Object.keys(t))u[p]=t[p];const c=o.config;c.customObjects=u;const h=Object.assign({},In);for(const p of Object.keys(t))In[p]=t[p];ud(o.config);const d=l(i,o.config,t,r);return In=Object.assign({},h),d}else{const u=Object.assign({},In);for(const h of Object.keys(t))In[h]=t[h];const c=new i(o.config);return In=Object.assign({},u),c}}}function a_(n,e){return ne?1:0}function sl(n,e){return-1*a_(n,e)}function qs(n){if(n==null)return n;const e=[];for(const t of n)e.indexOf(t)===-1&&e.push(t);return e}function i_(n){if(n==null)throw new L(`Invalid value in obj: ${JSON.stringify(n)}`);for(const e in n)if(n.hasOwnProperty(e))return!1;return!0}function eo(n,e,t){if(t!=null&&n.indexOf(t)<0)throw new L(`${t} is not a valid ${e}. Valid values are ${n} or null/undefined.`)}function fm(n,e,t=0,s=1/0){return Jn(t>=0),Jn(s>=t),Array.isArray(n)&&n.length>=t&&n.length<=s&&n.every(r=>typeof r===e)}function xt(n,e){Array.isArray(n)?(I(n.length>0,()=>`${e} is unexpectedly an empty array.`),n.forEach((t,s)=>xt(t,`element ${s+1} of ${e}`))):I(Number.isInteger(n)&&n>0,()=>`Expected ${e} to be a positive integer, but got ${t1(n)}.`)}function t1(n){return n===null?"null":Array.isArray(n)?"["+n.map(e=>t1(e)).join(",")+"]":typeof n=="string"?`"${n}"`:`${n}`}function l_(n,e,t){let s=t!=null?t():Nt(),r;return(...a)=>{const i=t!=null?t():Nt();return i-s0){const t=`${n}_${e}`;return lo.set(t,1),t}else return n}const y_=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function i1(n){return!!n.match(y_)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function b_(n){return n===parseInt(n.toString(),10)}function Ks(n,e,t){e==null&&(e=0),t==null&&(t=n.length);let s=1;for(let r=e;re&&(e=s)}return e}function Hn(n,e){if(e{if(n.shape.length!==2)throw new L(`repeat() expects a rank-2 tensor, but received a rank-${n.shape.length} tensor.`);const t=Vi(n,1);return cd(t,[1,e,1])})}function w_(n){const e=[Ks(n.shape)];return F(n,e)}function v_(n){if(n.rank<=1)throw new L(`batchFlatten requires a minimum rank of 2. Got rank: ${n.rank}.`);const e=[n.shape[0],Ks(n.shape,1)];return F(n,e)}function Ar(n,e,t){return z(()=>{switch(n.rank){case 1:return Tc(n,e,t);case 2:return Af(n,[e,0],[t,n.shape[1]]);case 3:return Ec(n,[e,0,0],[t,n.shape[1],n.shape[2]]);case 4:return Sa(n,[e,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3]]);case 5:return Te(n,[e,0,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3],n.shape[4]]);case 6:return Te(n,[e,0,0,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3],n.shape[4],n.shape[5]]);default:throw new L(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Rh(n,e,t){return z(()=>{switch(n.rank){case 1:return Tc(n,e,t);case 2:return Af(n,[0,e],[n.shape[0],t]);case 3:return Ec(n,[0,0,e],[n.shape[0],n.shape[1],t]);case 4:return Sa(n,[0,0,0,e],[n.shape[0],n.shape[1],n.shape[2],t]);default:throw new L(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function ol(n,e,t,s){return z(()=>{switch(n.rank){case 1:return Tc(n,e,t);case 2:switch(s){case 1:return Ar(n,e,t);case 2:return Rh(n,e,t);default:throw new L(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Ar(n,e,t);case 2:return Ec(n,[0,e,0],[n.shape[0],t,n.shape[2]]);case 3:return Rh(n,e,t);default:throw new L(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Ar(n,e,t);case 2:return Sa(n,[0,e,0,0],[n.shape[0],t,n.shape[2],n.shape[3]]);case 3:return Sa(n,[0,0,e,0],[n.shape[0],n.shape[1],t,n.shape[3]]);case 4:return Rh(n,e,t);default:throw new L(`The axis is not within the rank of the tensor ${s}`)}default:throw new L(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function mm(n,e=-1){let t;return e<0&&(t=n[0].rank,t!==0?e=t:e=0),e===n[0].rank&&(e=-1),at(n,e)}function Qy(n,e){switch(n.rank){case 1:return cw([n,e]);case 2:return hw([n,e],0);case 3:return dw([n,e],0);case 4:return pw([n,e],0);default:throw new L(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}}function cd(n,e){if(Array.isArray(e)||(e=[e]),n.rank!==e.length)throw new L(`The length of input n (${e.length}) does not match the number of dimensions in input x (${n.rank})`);return kn(n,e)}function Kc(n,e=0,t=1,s,r){return $f(n,e,t,s,r)}function as(n,e,t,s){if(n.rank<2||e.rank<2)throw new xe(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${e.shape}`);if(e.rank>=3){const r=n.shape.slice(-1)[0],o=e.shape.slice(-2)[0];if(r!==o)throw new xe(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and y shape = ${e.shape}`)}if(n.rank===2&&e.rank===2)return rd({a:n,b:e,transposeA:!1,transposeB:!1,bias:s?hd(n.rank,s,jn()):null,activation:t});{const r=n.shape.slice(),o=r.pop();n=F(n,[-1,o]);const a=e.shape.slice(),i=a.pop(),l=a.pop(),u=[...a,i],c=Array.from({length:e.rank},(f,g)=>g===0?e.rank-2:g<=e.rank-2?g-1:g);e=F(ke(e,c),[l,-1]);const h=[...r,...u];return F(rd({a:n,b:e,transposeA:!1,transposeB:!1,bias:s?hd(n.rank,s,jn()):null,activation:t}),h)}}function l1(n,e,t){return z(()=>(Array.isArray(e)?e=Pt(e,"int32"):e=ee(e,"int32"),Li(n,e,t)))}function Wi(n){return O(n,n)}function hd(n,e,t){const s=e.shape;if(e.rank!==1&&e.rank!==n)throw new L(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${n}`);if(n===5){if(t==="channelsFirst")return s.length===1?F(e,[1,s[0],1,1,1]):F(e,[1,s[3],s[0],s[1],s[2]]);if(t==="channelsLast")return s.length===1?F(e,[1,1,1,1,s[0]]):F(e,[1].concat(s))}else if(n===4){if(t==="channelsFirst")return s.length===1?F(e,[1,s[0],1,1]):F(e,[1,s[2],s[0],s[1]]);if(t==="channelsLast")return s.length===1?F(e,[1,1,1,s[0]]):F(e,[1].concat(s))}else if(n===3){if(t==="channelsFirst")return s.length===1?F(e,[1,s[0],1]):F(e,[1,s[1],s[0]]);if(t==="channelsLast")return s.length===1?F(e,[1,1,s[0]]):F(e,[1].concat(s))}else if(n<3)return e;throw new L(`Unsupported input rank by biasAdd: ${e.rank}`)}function Xn(n,e,t){return z(()=>(t==null&&(t=jn()),rt(t),Y(n,hd(n.rank,e,t))))}function $_(n,e=1){if(e!==1)throw new xe(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return Oi(n)}function S_(n){return z(()=>ce(n,Y(lt(n),1)))}function u1(n,e,t,s){return z(()=>qw(n,e,t,s))}function I_(n){return z(()=>{const e=Y(.5,O(.2,n));return ln(e,0,1)})}function Ui(n,e,t=!1){return t?n():e()}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const N_=["fanIn","fanOut","fanAvg"],C_=["normal","uniform","truncatedNormal"];/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function k_(n){eo(N_,"FanMode",n)}function T_(n){eo(C_,"Distribution",n)}class On extends Qr{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class gm extends On{apply(e,t){return ct(e,t)}}gm.className="Zeros";Z(gm);class Xc extends On{apply(e,t){return rn(e,t)}}Xc.className="Ones";Z(Xc);class ym extends On{constructor(e){if(super(),typeof e!="object")throw new L(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new L(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return z(()=>O(pe(this.value),rn(e,t)))}getConfig(){return{value:this.value}}}ym.className="Constant";Z(ym);class bm extends On{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Zr(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}bm.className="RandomUniform";Z(bm);class xm extends On{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new xe(`randomNormal does not support dType ${t}.`);return Kc(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}xm.className="RandomNormal";Z(xm);class wm extends On{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new xe(`truncatedNormal does not support dType ${t}.`);return _f(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}wm.className="TruncatedNormal";Z(wm);class vm extends On{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return z(()=>{if(e.length!==2||e[0]!==e[1])throw new L("Identity matrix initializer can only be used for 2D square matrices.");return O(this.gain,mf(e[0]))})}getConfig(){return{gain:this.gain}}}vm.className="Identity";Z(vm);function E_(n,e="channelsLast"){let t,s;if(rt(e),n.length===2)t=n[0],s=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(e==="channelsFirst"){const r=Ks(n,2);t=n[1]*r,s=n[0]*r}else if(e==="channelsLast"){const r=Ks(n,0,n.length-2);t=n[n.length-2]*r,s=n[n.length-1]*r}}else{const r=Ks(n);t=Math.sqrt(r),s=Math.sqrt(r)}return[t,s]}class Yt extends On{constructor(e){if(super(),e.scale<0)throw new L(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,k_(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,T_(this.distribution),this.seed=e.seed}apply(e,t){const s=E_(e),r=s[0],o=s[1];let a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,r):this.mode==="fanOut"?a/=Math.max(1,o):a/=Math.max(1,(r+o)/2),this.distribution==="normal"){const i=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new xe(`${this.getClassName()} does not support dType ${t}.`);return _f(e,0,i,t,this.seed)}else{const i=Math.sqrt(3*a);return Zr(e,-i,i,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Yt.className="VarianceScaling";Z(Yt);class Yc extends Yt{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Yt.className}}Yc.className="GlorotUniform";Z(Yc);class Zc extends Yt{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Yt.className}}Zc.className="GlorotNormal";Z(Zc);class Jc extends Yt{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Yt.className}}Jc.className="HeNormal";Z(Jc);class Qc extends Yt{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Yt.className}}Qc.className="HeUniform";Z(Qc);class eh extends Yt{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Yt.className}}eh.className="LeCunNormal";Z(eh);class th extends Yt{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Yt.className}}th.className="LeCunUniform";Z(th);class $m extends On{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return z(()=>{if(e.length<2)throw new xe("Shape must be at least 2D.");if(t!=="int32"&&t!=="float32"&&t!==void 0)throw new TypeError(`Unsupported data type ${t}.`);t=t;const s=G(e.slice(0,-1)),r=e[e.length-1],o=s*r;o>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${o}) elements: Slowness may result.`);const a=[Math.max(r,s),Math.min(r,s)],i=Kc(a,0,1,t,this.seed),l=n0.qr(i,!1);let u=l[0];const h=l[1].flatten().stridedSlice([0],[Math.min(r,s)*Math.min(r,s)],[Math.min(r,s)+1]);return u=O(u,h.sign()),ss*r);return e}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const nb="Variable";class A_{constructor(e,t="float32",s=nb,r=!0,o=null){this.dtype=t??"float32",this.shape=e.shape,this.id=s1(),s=s??nb,this.originalName=o1(s),this.name=a1(this.originalName),this.trainable_=r,this.constraint=o,this.val=Hw(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),R_(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function R_(n,e){if(n.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(n.shape)+" vs. "+JSON.stringify(e.shape))}function pd(n){return n.map(e=>e.read())}function Sm(n){n.forEach(e=>{e[0].write(e[1])})}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class dt{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class us{constructor(e,t,s,r,o,a,i){this.dtype=e,this.shape=t,this.sourceLayer=s,this.inputs=r,this.callArgs=o,this.outputTensorIndex=i,this.id=s1(),a!=null&&(this.originalName=o1(a),this.name=a1(this.originalName)),this.rank=t.length}}let D_=0;class nh{constructor(e,t){this.callArgs=t,this.id=D_++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const s of e.inboundLayers)s!=null&&s.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let O_=0;class Ie extends Qr{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=O_++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const s=this.getClassName();t=gs(s)+"_"+qc(s)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let s;if(e.batchInputShape!=null)s=e.batchInputShape;else if(e.inputShape!=null){let o=null;e.batchSize!=null&&(o=e.batchSize),s=[o].concat(e.inputShape)}this.batchInputShape=s;let r=e.dtype;r==null&&(r=e.inputDType),r==null&&(r="float32"),this.dtype=r}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Tn(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new L(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return jt(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return jt(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Zn(`Layer ${this.name} is not connected, no input to return.`);return jt(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Zn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return jt(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){const t=_e(e);if(this.inputSpec==null||this.inputSpec.length===0)return;const s=_e(this.inputSpec);if(t.length!==s.length)throw new L(`Layer ${this.name} expects ${s.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let r=0;ra.maxNDim)throw new L(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${i}`);if(a.minNDim!=null&&i=0?l[c]:l[l.length+c];if(h!=null&&[h,null].indexOf(d)===-1)throw new L(`Input ${r} is incompatible with layer ${this.name}: expected axis ${c} of input shape to have value ${h} but got shape ${l}.`)}}if(a.shape!=null)for(let l=0;l{if(!this.built){this.assertInputCompatibility(e);const a=[];for(const i of _e(e))a.push(i.shape);this.build(jt(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&o&&(this._refCount=1)}if(this.assertInputCompatibility(e),o){let a=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,a);const i=_e(a),l=[];for(let u of i)s.indexOf(u)!==-1&&(u=u.clone()),l.push(u);if(a=jt(l),this.activityRegularizer!=null)throw new xe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{const a=__(e),i=this.computeOutputShape(a);let l;const u=F_(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),i!=null&&i.length>0&&Array.isArray(i[0])?l=i.map((c,h)=>new us(u,c,this,_e(e),t,this.name,h)):l=new us(u,i,this,_e(e),t,this.name),this.addInboundNode(e,l,null,null,a,i,t),this._refCount++,this.activityRegularizer!=null)throw new xe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return l}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((s,r)=>{s!=null&&e[r]!=null&&e[r]!==s&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Zn(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const s=JSON.stringify(t.outputShapes);e.indexOf(s)===-1&&e.push(s)}if(e.length===1){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new Zn(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Tn(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Gl(this.weights)}build(e){this.built=!0}getWeights(e=!1){return pd(e?this.trainableWeights:this.weights)}setWeights(e){z(()=>{const t=this.weights;if(t.length!==e.length)throw new L(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;const s=[],r=pd(t);for(let o=0;oo.apply(c.read())),a==null&&(a=!0),a?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=_e(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(s=>{if(s!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}setMaskMetadata(e,t,s){if(!this.supportsMasking)return;const r=this.computeMask(e,s),o=_e(t),a=_e(r);if(o.length!==a.length)throw new Error(`${this.name} outputs ${o.length} tensors but ${o.length} masks for those tensors`);for(let i=0;ie.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function __(n){n=_e(n);const e=[];for(const t of n)e.push(t.shape);return jt(e)}function F_(n){return"float32"}function c1(n,e,t){if((e==null||t!=null&&t>0)&&(e=n.sourceLayer,t=n.nodeIndex),e.inboundNodes.length===0)return[n];{const s=e.inboundNodes[t];if(s.inboundLayers.length===0)return s.inputTensors;{const r=[];for(let o=0;of.name),l=[],u=e.names();for(const f of i)u.indexOf(f)!==-1?l.push(e.getValue(f)):l.push(null);const c=i.join(",")+"|"+e.names().sort().join(",");let h=Hl.get(c),d;if(h==null){const f=B_(a,e);h=f.sorted,d=f.recipientCounts,Hl.put(c,h),jl.put(c,d)}d={},r||Object.assign(d,jl.get(c));const p=new Us(e);for(let f=0;f0,()=>"Expected at least one fetch, got none");let t=[],s={};if(n.length===1){const r=sb(n[0],e);t=r.sorted,s=r.recipientMap}else{const r=new Set;for(const o of n){const{sorted:a,recipientMap:i}=sb(o,e);for(const l of a)r.has(l.name)||(t.push(l),r.add(l.name));for(const l in i)s[l]==null&&(s[l]=new Set),i[l].forEach(u=>s[l].add(u))}}return{sorted:t,recipientCounts:V_(s)}}function V_(n){const e={};for(const t in n)e[t]=n[t].size;return e}function sb(n,e){const t=new Set,s=[],r={};for(const i of e.names())t.add(i);const o=[],a=[];for(o.push(n);o.length>0;){const i=o[o.length-1];if(t.has(i.name)){o.pop();continue}const l=a[a.length-1]===o.length-1;if(i.inputs.length===0||l)o.pop(),s.push(i),t.add(i.name),l&&a.pop();else{a.push(o.length-1);for(const u of i.inputs)r[u.name]==null&&(r[u.name]=new Set),r[u.name].add(i.name),!t.has(u.name)&&o.push(u)}}return{sorted:s,recipientMap:r}}function W_(n){let e;if(n.sourceLayer.inboundNodes.length===1)e=n.sourceLayer.output;else{let t=null;for(let s=0;s100,M_);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Im(n,e){return z(()=>At(ie(O(n,n),e,!0)))}class Gi extends Qr{getConfig(){return{}}}class Nm extends Gi{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return z(()=>{const t=Im(e,this.axis),s=ln(t,0,this.maxValue);return O(e,ce(s,Y(ht(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Nm.className="MaxNorm";Z(Nm);class Cm extends Gi{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return z(()=>ce(e,Y(ht(),Im(e,this.axis))))}getConfig(){return{axis:this.axis}}}Cm.className="UnitNorm";Z(Cm);class km extends Gi{apply(e){return hs(e)}}km.className="NonNeg";Z(km);class Tm extends Gi{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return z(()=>{const t=Im(e,this.axis),s=Y(O(this.rate,ln(t,this.minValue,this.maxValue)),O(1-this.rate,t));return O(e,ce(s,Y(ht(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Tm.className="MinMaxNorm";Z(Tm);const rb={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ft(n){return pm(n)}function ob(n,e={}){return Bi(n,mn.getMap().classNameMap,e,"constraint")}function mt(n){if(n==null)return null;if(typeof n=="string"){const t={className:n in rb?rb[n]:n,config:{}};return ob(t)}else return n instanceof Gi?n:ob(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function G_(n){return new Nm(n)}function H_(n){return new Cm(n)}function j_(){return new km}function q_(n){return new Tm(n)}const PJ=Object.freeze(Object.defineProperty({__proto__:null,maxNorm:G_,minMaxNorm:q_,nonNeg:j_,unitNorm:H_},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function K_(){return new gm}function X_(){return new Xc}function Y_(n){return new ym(n)}function Z_(n){return new bm(n)}function J_(n){return new xm(n)}function Q_(n){return new wm(n)}function eF(n){return new vm(n)}function tF(n){return new Yt(n)}function nF(n){return new Yc(n)}function sF(n){return new Zc(n)}function rF(n){return new Jc(n)}function oF(n){return new Qc(n)}function aF(n){return new eh(n)}function iF(n){return new th(n)}function lF(n){return new $m(n)}const zJ=Object.freeze(Object.defineProperty({__proto__:null,constant:Y_,glorotNormal:sF,glorotUniform:nF,heNormal:rF,heUniform:oF,identity:eF,leCunNormal:aF,leCunUniform:iF,ones:X_,orthogonal:lF,randomNormal:J_,randomUniform:Z_,truncatedNormal:Q_,varianceScaling:tF,zeros:K_},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */async function Bs(n){if(n==null)return;const e=[],t=[],s=[];for(const r in n){const o=n[r];if(typeof o!="number"){const a=o;e.push(a.data()),t.push(r),s.push(a)}}if(e.length>0){const r=await Promise.all(e);for(let o=0;oY(this.totals[r],O(o,s)));this.totals[r]=i,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const s of this.params.metrics)this.totals[s]!=null&&(typeof this.totals[s]=="number"?t[s]=this.totals[s]/this.seen:z(()=>{const r=O(ce(1,this.seen),this.totals[s]);t[s]=r,this.totals[s].dispose(),bt(t[s])}))}}class dF extends No{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const s in t)this.history[s]==null&&(this.history[s]=[]),this.history[s].push(t[s])}async syncData(){const e=[],t=[],s=[];for(const o in this.history){const a=this.history[o];for(let i=0;inew pF(s,e))}class pn{constructor(){}static registerCallbackConstructor(e,t){I(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),pn.checkForDuplicate(t),pn.constructors[e]==null&&(pn.constructors[e]=[]),pn.constructors[e].push(t)}static checkForDuplicate(e){for(const t in pn.constructors)pn.constructors[+t].forEach(r=>{if(r===e)throw new L("Duplicate callback constructor.")})}static clear(){pn.constructors={}}static createCallbacks(e){const t=[];for(const s in pn.constructors){const r=+s;e>=r&&t.push(...pn.constructors[r])}return t.map(s=>new s)}}pn.constructors={};function f1(n,e,t,s,r,o,a,i,l){const u=new dF,c=[new hF,...pn.createCallbacks(e)];n!=null&&c.push(...n),c.push(u);const h=new cF(c);return h.setParams({epochs:t,initialEpoch:s,samples:r,steps:o,batchSize:a,verbose:e,doValidation:i,metrics:l}),{callbackList:h,history:u}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Wn(n,e={},t=!1){return Bi(n,mn.getMap().classNameMap,e,"layer",t)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function ql(n,e){return z(()=>{n.dtype!=="float32"&&(n=ee(n,"float32"));const t=ie(Wi(n),e,!0),s=Do(t.shape,ht()),r=At(Os(t,s));return ce(n,r)})}function to(n,e){return z(()=>et(Wi(ae(e,n)),-1))}function sh(n,e){return z(()=>et(lt(ae(e,n)),-1))}function zo(n,e){return z(()=>{const t=ae(n,e),s=ln(lt(n),ht(),Number.MAX_VALUE),r=lt(ce(t,s));return O(100,et(r,-1))})}function fF(n,e){return z(()=>{const t=ln(e,ht(),Number.MAX_VALUE),s=vn(Y(1,t)),r=ln(n,ht(),Number.MAX_VALUE),o=vn(Y(1,r));return et(Wi(ae(s,o)),-1)})}function mF(n,e){return z(()=>{const t=Os(0,ae(1,O(n,e)));return et(Wi(t),-1)})}function gF(n,e){return z(()=>{const t=Os(0,ae(1,O(n,e)));return et(t,-1)})}function yF(n,e){return z(()=>{const t=ie(O(n,e),-1),s=En(O(ae(1,n),e),-1);return Os(0,Y(1,ae(s,t)))})}function bF(n,e){return z(()=>{const t=Math.log(2),s=ae(e,n),r=ae(Y(s,Oo(O(-2,s))),t);return et(r,-1)})}function Na(n,e,t=!1){return z(()=>{if(t)e=Ac(e);else{const s=ie(e,e.shape.length-1,!0);e=ce(e,s)}return e=ln(e,ht(),1-ht()),Ge(ie(O(ee(n,"float32"),vn(e)),e.shape.length-1))})}function Kl(n,e,t=!1){return z(()=>{const s=ee(Fi(w_(n)),"int32");e=ln(e,ht(),1-ht());const r=e.shape,o=F(va(s,r[r.length-1]),r);return Na(o,e,t)})}function xF(n,e){if(!Ce(n.shape,e.shape))throw new L(`logits and labels must have the same shape, but got shapes ${JSON.stringify(n.shape)} and ${JSON.stringify(e.shape)}`);return z(()=>{const t=hs(e),s=Ge(lt(e));return Y(ae(t,O(e,n)),wc(un(s)))})}function rh(n,e){return z(()=>{let t;return t=ln(e,ht(),1-ht()),t=vn(ce(t,ae(1,t))),et(xF(n,t),-1)})}function wF(n,e){return z(()=>{const t=ln(n,ht(),1),s=ln(e,ht(),1);return ie(O(n,vn(ce(t,s))),-1)})}function vF(n,e){return z(()=>{const t=vn(Y(ht(),e));return et(ae(e,O(n,t)),-1)})}function Em(n,e){return z(()=>{const t=ql(n,-1),s=ql(e,-1),r=O(t,s);return Ge(ie(r,-1))})}const Xl={meanSquaredError:to,meanAbsoluteError:sh,meanAbsolutePercentageError:zo,meanSquaredLogarithmicError:fF,squaredHinge:mF,hinge:gF,categoricalHinge:yF,logcosh:bF,categoricalCrossentropy:Na,sparseCategoricalCrossentropy:Kl,binaryCrossentropy:rh,kullbackLeiblerDivergence:wF,poisson:vF,cosineProximity:Em};function Dh(n){if(typeof n=="string"){if(n in Xl)return Xl[n];let e=`Unknown loss ${n}`;throw n.toLowerCase().includes("softmaxcrossentropy")&&(e=`Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new L(e)}else return n}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Am(n,e){return z(()=>{const t=O(.5,$n(e)),s=os(Jt(e,t),n.dtype);return et(wn(n,s),-1)})}function Rm(n,e){return z(()=>os(wn(vo(n,-1),vo(e,-1)),"float32"))}function m1(n,e){return z(()=>ee(ie(Gn(wn(n,1),wn(e,1))),"float32"))}function $F(n,e){return z(()=>ee(ie(Gn(wn(n,1),wn(e,0))),"float32"))}function SF(n,e){return z(()=>ee(ie(Gn(wn(n,0),wn(e,1))),"float32"))}function g1(n,e){return z(()=>{const t=m1(n,e),s=SF(n,e),r=Y(t,s);return ee(Tt(Jt(r,0),ce(t,r),0),"float32")})}function IF(n,e){return z(()=>{const t=m1(n,e),s=$F(n,e),r=Y(t,s);return ee(Tt(Jt(r,0),ce(t,r),0),"float32")})}function y1(n,e){return rh(n,e)}function b1(n,e){return n.rank===e.rank&&(n=Jr(n,[n.rank-1])),e=vo(e,-1),e.dtype!==n.dtype&&(e=ee(e,n.dtype)),ee(wn(n,e),"float32")}function NF(n,e){return z(()=>{const t=n.sub(e).square().sum(),s=n.sub(n.mean()).square().sum();return pe(1).sub(t.div(s))})}const CF=to,kF=to,TF=sh,EF=sh,AF=zo,RF=zo,Dm=Na,DF=Em,x1=Kl,Yl={binaryAccuracy:Am,categoricalAccuracy:Rm,precision:g1,categoricalCrossentropy:Dm,sparseCategoricalCrossentropy:x1,mse:CF,MSE:kF,mae:TF,MAE:EF,mape:AF,MAPE:RF,cosine:DF};function OF(n){if(typeof n=="string"&&n in Yl)return Yl[n];if(typeof n!="string"&&n!=null)return n;throw new L(`Unknown metric ${n}`)}function al(n){if(Jn(n!==null,`Unknown LossOrMetricFn ${n}`),typeof n=="string")return n;{let e;for(const t of Object.keys(Xl))if(Xl[t]===n){e=t;break}if(e!==void 0)return e;for(const t of Object.keys(Yl))if(Yl[t]===n){e=t;break}return e!==void 0?e:n.name}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function _F(n){const e={Adagrad:()=>io.adagrad(.01),Adadelta:()=>io.adadelta(1,.95,ht()),Adam:()=>io.adam(.001,.9,.999,ht()),Adamax:()=>io.adamax(.002,.9,.999,ht(),0),RMSProp:()=>io.rmsprop(.001,.9,0,ht()),SGD:()=>io.sgd(.01)};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,n in e)return e[n]();throw new L(`Unknown Optimizer ${n}`)}/** + * @license + * Copyright 2019 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const ib=1*1024*1024;function lb(n,e,t=!1){if(n==null||typeof n!="object"||Object.getPrototypeOf(n)!==Object.prototype||!fd(n))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(t){const s=JSON.stringify(n);s.length>ib&&console.warn(`User-defined metadata of model "${e}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${ib}.`)}}function fd(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){const e=Object.keys(n);for(const t of e)if(typeof t!="string"||!fd(n[t]))return!1;return!0}else if(Array.isArray(n)){for(const e of n)if(!fd(e))return!1;return!0}else return!1;else{const e=typeof n;return e==="string"||e==="number"||e==="boolean"}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function FF(n,e,t,s=console.log){const r=PF(n),o=["Layer (type)","Input Shape","Output shape","Param #"];r?(e=e||90,t=t||[.32,.61,.89,1]):(e=e||115,t=t||[.24,.48,.7,.8,1]),t[t.length-1]<=1&&(t=t.map(c=>Math.floor(e*c)));let a;if(!r){o.push("Receives inputs"),a=[];for(const c in n.nodesByDepth)a.push(...n.nodesByDepth[c])}s("_".repeat(e)),Zl(o,t,s),s("=".repeat(e));const i=n.layers;for(let c=0;c1||r.length===1&&r[0].inboundLayers.length>1){e=!1;break}s.push(...r)}if(e)for(const r of n.layers){let o=!1;for(const a of r.inboundNodes)if(s.indexOf(a)!==-1)if(o){e=!1;break}else o=!0;if(!e)break}return e}function Zl(n,e,t=console.log){let s="";for(let r=0;r0&&(s=s.slice(0,s.length-1)+" "),s+=n[r],s=s.slice(0,e[r]),s+=" ".repeat(e[r]-s.length);t(s)}function zF(n,e,t){let s,r;try{r=n.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch{r="multiple"}try{s=JSON.stringify(n.outputShape)}catch{s="multiple"}const o=n.name,a=n.getClassName(),i=[`${o} (${a})`,r,s,n.countParams().toString()];Zl(i,e,t)}function MF(n,e,t,s){let r,o;try{o=n.inboundNodes.map(h=>JSON.stringify(h.inputShapes)).join(",")}catch{o="multiple"}try{r=JSON.stringify(n.outputShape)}catch{r="multiple"}const a=[];for(const h of n.inboundNodes)if(!(t!=null&&t.length>0&&t.indexOf(h)===-1))for(let d=0;d{const e=Object.keys(n);if(e.length===0)return!1;const t=e[0].split("/");return!isNaN(parseInt(t[t.length-1],10))};class Pn extends Ie{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){const b=this.getClassName().toLowerCase();this.name=qc(b)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],qs(this.inputs).length!==this.inputs.length)throw new L(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);qs(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(b=>b.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const b of this.outputs){const w=b.sourceLayer,x=b.nodeIndex,$=b.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push($)}for(const b of this.inputs){const w=b.sourceLayer,x=b.nodeIndex,$=b.tensorIndex;Jn(x===0,"input layer has >1 nodes"),Jn($===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push($)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;bb.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);const t={},s={},r={},o={},a={},i=[],l=(b,w,x,$,C,E)=>{($==null||C==null||E==null)&&($=b.sourceLayer,C=b.nodeIndex,E=b.tensorIndex);const A=$.inboundNodes[C];if(x.indexOf(A)!==-1)throw new Tn(`The tensor ${b.name} at layer "${$.name}" is part of a cycle.`);if(w.indexOf(A)!==-1)return;this.containerNodes.add(Pn.nodeKey($,C)),$.id in a||(a[$.id]=Object.keys(a).length),x.indexOf(A)===-1&&x.push(A);const k=A.inboundLayers.length;for(let T=0;T=0;)x.splice(x.indexOf(A),1);i.push(A)},u=[],c=[];for(const b of this.outputs)l(b,u,c);const h=i.slice().reverse();for(const b of h){s[b.id]=b,b.id in t||(t[b.id]=0);let w=t[b.id];const x=r[b.outboundLayer.id]==null?0:r[b.outboundLayer.id];w=Math.max(w,x),r[b.outboundLayer.id]=w,o[b.outboundLayer.id]=b.outboundLayer,t[b.id]=w;for(let $=0;$parseInt(b,10)).sort(sl);this.layers=[];for(const b of f){const w=p[b];w.sort((x,$)=>{const C=a[x.id],E=a[$.id];return CE?1:0});for(const x of w)x instanceof Pn&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,f=Object.keys(d).map(b=>parseInt(b,10)).sort(sl);const g=this.inputs.slice(),m=[];for(const b of f)for(const w of d[b]){const x=w.outboundLayer;if(x!=null){for(const $ of w.inputTensors)if(g.indexOf($)===-1)throw new Tn(`Graph disconnected: cannot obtain value for tensor ${$} at layer "${x.name}". The following previous layers were accessed without issue: ${m}`);for(const $ of w.outputTensors)g.push($);m.push(x.name)}}this.nodesByDepth=d;const y=this.layers.map(b=>b.name);for(const b of y){const w=y.filter(x=>x===b).length;if(w!==1)throw new Tn(`The name "${b}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(y))}this.outboundNodes=[],this.inboundNodes=[],new nh({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(b=>null),outputMasks:this.outputs.map(b=>null),inputShapes:this.inputs.map(b=>b.shape),outputShapes:this.outputs.map(b=>b.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(s=>s.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new L("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const s of this.layers)t.push(...s.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const s={};let r=0;const o=BF(e);o&&this.parseWeights(e);for(const i of this.layers)for(const[l,u]of i.weights.entries()){const c=o?`${u.name.split("/").slice(0,-1).join("/")+"/"}${l}`:u.originalName;if(s[c]!=null)throw new L(`Duplicate weight name: ${c}`);s[c]=u,r++}const a=[];for(const i in e){let l=i;if(s[i]==null){const u=i.split("/");l=u.slice(0,-2).concat([u[u.length-1]]).join("/")}if(s[l]!=null)a.push([s[l],e[i]]);else if(t)throw new L(`Provided weight data has no target variable: ${i}`);delete s[l]}if(t){const i=[];for(const l in s)i.push(l);if(i.length>0)throw new L(`${i.length} of ${r} weights are not set: ${i}`)}Sm(a)}parseWeights(e){for(const t in Object.keys(e)){const s=t.split("/"),r=["vars","layer_checkpoint_dependencies"],o=s.map(a=>a.startsWith("_")?a.slice(1):a).filter(a=>!r.includes(a)).join("/");o!==t&&(e[o]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Om}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const s=md(this.updatedConfig());return t?JSON.stringify(s):s}call(e,t){return z(()=>{e=_e(e);const s=new Us;for(let r=0;r{e=_e(e);let s;return t==null?s=Br(null,e.length):s=_e(t),this.runInternalGraph(e,s)[1]})}computeOutputShape(e){const t=Ul(e);if(t.length!==this.inputLayers.length)throw new L(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let i=0;iparseInt(i,10)).sort(sl);if(r.length>1)for(const i of r){const l=this.nodesByDepth[i];for(const u of l){const c=u.outboundLayer;if(this.inputLayers.map(g=>g.id).indexOf(c.id)!==-1)continue;const h=[];for(let g=0;gparseInt(l,10)).sort(sl);for(const l of r){const u=this.nodesByDepth[l];for(const c of u){const h=c.outboundLayer,d=c.inputTensors,p=c.outputTensors,f=new Array;for(const g of d)g.id in s&&f.push(s[g.id]);if(f.length===d.length){let g={},m,y,b,w;if(c.callArgs!=null&&(g=c.callArgs),f.length===1){const[x,$]=f[0];g.mask==null&&(g.mask=$),b=_e(h.call(x,g)),w=_e(h.computeMask(x,$)),m=[x],y=[$]}else m=f.map(x=>x[0]),y=f.map(x=>x[1]),g.mask==null&&(g.mask=y),b=_e(h.call(m,g)),w=_e(h.computeMask(m,y));if(h.activityRegularizer)throw new xe("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x{const e=[];for(const t of this.layers)for(let s=0;s0){const g=[];for(let m=0;m0&&m.apply(jt(b),w)}function u(m){const y=m.name,b=Wn(m,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(r),o[y]=b,m.inboundNodes.forEach(x=>{if(!(x instanceof Array))throw new L(`Corrupted configuration, expected array for nodeData: ${x}`);i(b,x)})}const c=t.name,h=t.layers;for(const m of h)u(m);for(;!i_(a);)for(const m of h){const y=o[m.name];if(y.name in a){const b=a[y.name];delete a[y.name];for(const w of b)l(y,w)}}const d=[],p=[],f=t.inputLayers;for(const m of f){const y=m[0],b=m[1],w=m[2];Jn(y in o);const $=o[y].inboundNodes[b].outputTensors;d.push($[w])}const g=t.outputLayers;for(const m of g){const y=m[0],b=m[1],w=m[2];Jn(y in o);const $=o[y].inboundNodes[b].outputTensors;p.push($[w])}return new e({inputs:d,outputs:p,name:c})}get stateful(){if(this._stateful)throw new L("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){z(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function VF(n,e,t){const s=e.length;if(n==null||Array.isArray(n)&&n.length===0)return e.map(r=>null);if(s===1)return Array.isArray(n)&&n.length===1?n:typeof n=="object"&&e[0]in n?[n[e[0]]]:[n];if(Array.isArray(n)){if(n.length!==s)throw new Error(`Provided ${t} is an array of ${n.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return n}else if(typeof n=="object"&&Object.keys(n).length>0&&typeof n[Object.keys(n)[0]]=="object"){const r=[];return e.forEach(o=>{o in n?r.push(n[o]):r.push(null)}),r}else throw new Error(`The model has multiple (${s}) outputs, so ${t} must be either an array with ${s} elements or an object with ${e} keys. Provided ${t} not understood: ${JSON.stringify(n)}`)}function v1(n,e){return VF(n,e,"classWeight")}async function $1(n,e,t,s){if(t!=null){const r=z(()=>{if(n.shape.length===1)return vs(n);if(n.shape.length===2){if(n.shape[1]>1)return vo(n,1);if(n.shape[1]===1)return F(n,[n.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),o=Array.from(await r.data());be(r);const a=[];return o.forEach(i=>{if(t[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);a.push(t[i])}),Pt(a,"float32")}else return null}function WF(n,e){return O(n,e)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const UF=32;function S1(n,e){let t,s;const r=e;t=r.xs,s=r.ys,I(t!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${e}`);const o=ub("input",n.inputNames,t),a=ub("output",n.outputNames,s),i=o[0].shape[0];I(o.length===n.inputs.length,()=>`LayersModel has ${n.inputs.length} inputs, but the dataset provides ${o.length} inputs. (Expected input keys: ${JSON.stringify(n.inputNames)})`),I(a.length===n.outputs.length,()=>`LayersModel has ${n.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(n.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${n.inputNames[l]} has ${o[l].shape[0]}; expected ${i} based on input ${n.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${n.outputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${n.inputNames[0]}.`);return{xs:o,ys:a}}function ub(n,e,t){if(t instanceof Re)return[t];if(Array.isArray(t))return I(t.length===e.length,()=>`Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${n} keys ${e}.`),t;{const s=[];for(const r of e){if(t[r]==null)throw new L(`The feature data generated by the dataset lacks the required ${n} key '${r}'.`);s.push(t[r])}return s}}function GF(n){if(n.length===3)throw new xe("Validation with sample weights is not implemented yet.");return{xs:n[0],ys:n[1]}}async function HF(n,e,t){const s=t.batchesPerEpoch!=null;if(I(n.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),I(t!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),I(t.epochs!=null&&t.epochs>0&&Number.isInteger(t.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${t.epochs}`),I(!s||t.batchesPerEpoch>0&&Number.isInteger(t.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${t.batchesPerEpoch}`),I(t.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0;try{const r=t.validationData!=null;let o,a;if(r)if(cb(t.validationData))I(t.validationBatches==null||t.validationBatches>0&&Number.isInteger(t.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${t.validationBatches}`);else{const m=GF(t.validationData);o=m.xs,a=m.ys}const i=n.makeTrainFunction(),l=n.getDedupedMetricsNames();let u;r?u=l.slice().concat(l.map(m=>"val_"+m)):u=l.slice();const c=p1(t.callbacks,t.yieldEvery),h=t.verbose==null?1:t.verbose,{callbackList:d,history:p}=f1(c,h,t.epochs,null,null,jF(e,t),null,r,u);d.setModel(n),n.history=p,await d.onTrainBegin(),n.stopTraining_=!1;let f=t.initialEpoch==null?0:t.initialEpoch,g=await e.iterator();for(;f=t.batchesPerEpoch:w.done){if(r){let x;cb(t.validationData)?x=_e(await n.evaluateDataset(t.validationData,{batches:t.validationBatches})):x=_e(n.evaluate(o,a,{batchSize:t.validationBatchSize==null?UF:t.validationBatchSize,verbose:0}));for(let $=0;$0)throw new xe("Verbose mode is not implemented yet.");I(!s||t.batches>0&&Number.isInteger(t.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(t.batches)}`);const a=qF(e)?e:await e.iterator();let i=0,l=0;for(;!s||l{if(u.value){const{xs:c,ys:h}=S1(n,u.value),d=c.concat(h),p=z(()=>r(d));if(be(d),l===0)for(let g=0;gY(o[g],O(f,m))),l>0&&be(y)}be(p),i+=f,++l}return o}),u.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${t.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u0&&Number.isInteger(n),()=>`batchSize is required to be a positive integer, but got ${n}`)}function ea(n,e,t){return n==null?[null]:Array.isArray(n)?n.map(s=>Ar(s,e,t-e)):Ar(n,e,t-e)}function gd(n,e){return z(()=>n==null?null:Array.isArray(n)?n.map(t=>gd(t,e)):l1(n,e.dtype==="int32"?e:ee(e,"int32")))}function _h(n,e){const t=[];let s=0,r=null;for(;s=n&&(r=n),t.push([s,r]),s=r;return t}function I1(n){const e=[];n instanceof Re&&(n=[n]);for(let t=0;tt.push(r.id));else if(e!=null)for(const r in e){const o=e[r];t.push(o.id)}const s=[];if(n instanceof Re)t.indexOf(n.id)===-1&&s.push(n);else if(Array.isArray(n))n.forEach(r=>{t.indexOf(r.id)===-1&&s.push(r)});else if(n!=null)for(const r in n){const o=n[r];t.indexOf(o.id)===-1&&s.push(o)}s.forEach(r=>{r.isDisposed||r.dispose()})}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function XF(n){return n instanceof Re}function yd(n){return Array.isArray(n)}function hb(n){return!XF(n)&&!yd(n)}function db(n,e,t,s=!0,r=""){if(e==null||e.length===0){if(n!=null){let a=!1;if(yd(n)&&n.length>0)a=!0;else if(hb(n)){for(const i in n)if(n.hasOwnProperty(i)){a=!0;break}}else a=!0;if(a)throw new L(`Error when checking model ${r} expected no data, but got ${n}`)}return[]}if(n==null)return e.map(a=>null);let o;if(hb(n)){n=n,o=[];for(const a of e){if(n[a]==null)throw new L(`No data provided for "${a}". Need data for each key in: ${e}`);o.push(n[a])}}else if(yd(n)){if(n=n,n.length!==e.length)throw new L(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${e.length} Tensor(s), but instead got the following list of Tensor(s): ${n}`);o=n}else{if(n=n,e.length>1)throw new L(`The model ${r} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);o=[n]}if(o=I1(o),t!=null)for(let a=0;a=0&&u!==c)throw new L(`${r} expected a batch of elements where each example has shape [${t[a].slice(1,t[a].length)}] (i.e.,tensor shape [*,${t[a].slice(1,t[a].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return o}function YF(n,e,t){const s=qs(n.map(o=>o.shape[0]));s.sort();const r=qs(e.map(o=>o.shape[0]));if(r.sort(),s.length>1)throw new L(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(n.map(o=>o.shape))}`);if(r.length>1)throw new L(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(o=>o.shape))}`);if(s.length>0&&r.length>0&&!Ce(s,r))throw new L(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}function ZF(n,e,t){const s=[to,rh,Na];for(let r=0;r1)throw new L(`The model expects ${e.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);o=[n]}if(t!=null)for(let a=0;a[]);let t;if(typeof n=="string"||typeof n=="function")t=[n];else if(Array.isArray(n)||typeof n=="object")t=n;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${n}`);if(Array.isArray(t))return e.map(s=>t);{const s=[];for(const r of e){let o=t.hasOwnProperty(r)?t[r]:[];Array.isArray(o)||(o=[o]),s.push(o)}return s}}const QF="layers-model";class Xs extends Pn{constructor(e){super(e),this.isTraining=!1}summary(e,t,s=console.log){if(!this.built)throw new L("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");FF(this,e,t,s)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=_F(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof fr))throw new L("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(const a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new L(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(const a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(Dh(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new L(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(i=>Dh(i))}else{const a=Dh(e.loss);this.outputs.forEach(i=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a{for(let a=0;a1&&(this.metricsTensors.push([i,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});const r=JF(e.metrics,this.outputNames),o=(a,i,l)=>{this.outputNames.length>1&&(i=this.outputNames[a]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([l,a])};Er("metric",()=>{for(let a=0;a{let h,d,p;for(const f of u){if(typeof f=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(f)!==-1){const m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===rh?["accuracy","acc"].indexOf(f)!==-1?d=Am:["crossentropy","ce"].indexOf(f)!==-1&&(d=y1):this.lossFunctions[a]===Kl?["accuracy","acc"].indexOf(f)!==-1?d=b1:["crossentropy","ce"].indexOf(f)!==-1&&(d=x1):["accuracy","acc"].indexOf(f)!==-1?d=Rm:["crossentropy","ce"].indexOf(f)!==-1&&(d=Dm);let y;["accuracy","acc"].indexOf(f)!==-1?y="acc":["crossentropy","ce"].indexOf(f)!==-1&&(y="ce"),p=d,h=""+y}else p=OF(f),h=""+al(f);let g;Er(h,()=>{g=p}),o(a,h,g)}})(i)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,s={}){const r=s.batchSize==null?32:s.batchSize;Oh(r);const a=this.standardizeUserDataXY(e,t,!0,r);try{const i=a[0].concat(a[1]);this.makeTestFunction();const l=this.testFunction,u=this.testLoop(l,i,r,s.verbose,s.steps);return jt(u)}finally{Ln(a[0],e),Ln(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),KF(this,e,t)}checkNumSamples(e,t,s,r="steps"){let o;if(s!=null){if(o=null,t!=null)throw new L(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?o=e[0].shape[0]:o=e.shape[0];else throw new L(`Either the input data should have a defined shape, or ${r} shoud be specified.`);return o}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new L("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(t),r=s?t:[t],o=this.retrieveSymbolicTensors(r),a=new Us;if(e instanceof Re&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new L(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let l=0;li.name);for(let i=0;i0){const r=[];throw t.forEach((o,a)=>{o==null&&r.push(e[a])}),new L(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(r)}`)}return t}predictLoop(e,t=32,s=!1){return z(()=>{const r=this.checkNumSamples(e);if(s)throw new xe("Verbose predictLoop() is not implemented yet.");const o=_h(r,t),a=this.outputs.map(i=>[]);for(let i=0;i{const u=o[i][0],c=o[i][1],h=ea(e,u,c),d=[];if(Array.isArray(h))for(let f=0;fa[c].push(u));return jt(a.map(i=>at(i,0)))})}predict(e,t={}){const s=I1(e);pb(s,this.inputNames,this.feedInputShapes,!1);try{const r=t.batchSize==null?32:t.batchSize;return Oh(r),this.predictLoop(s,r)}finally{Ln(s,e)}}predictOnBatch(e){pb(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,s=!0,r){if(this.optimizer_==null)throw new Tn("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const o=[];for(let a=0;a0&&e[0].shape[0]%r!==0)throw new L(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,s,r,o=!0,a){const[i,l]=this.standardizeUserDataXY(e,t,o,a);if(s!=null)throw new Error("sample weight is not supported yet.");let u=null;if(r!=null){const c=v1(r,this.outputNames);u=[];for(let h=0;h{const a=this.checkNumSamples(t,s,o,"steps"),i=[];if(r>0)throw new xe("Verbose mode is not implemented yet.");if(o!=null)throw new xe("steps mode in testLoop() is not implemented yet");{const l=_h(a,s),u=Pt(Hn(0,a));for(let c=0;c1){const a=Zy(e.slice(0,s),r);o+=`_${a}`}t.push(o)}return t}makeTrainFunction(){return e=>{const t=[],s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),o=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],i=()=>{const h=[];for(let g=0;g1&&g{f=Y(f,g)}),f},l=this.collectedTrainableWeights.map(h=>h.read());return[this.optimizer_.minimize(i,!0,l)].concat(a)}}makeTestFunction(){this.testFunction=e=>z(()=>{const t=[];let s;const r=e.slice(0,this.inputs.length),o=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let u=0;u0){if(m=!0,s.validationData.length===2)l=s.validationData[0],u=s.validationData[1];else throw s.validationData.length===3?new xe("validationData including sample weights is not supported yet."):new L(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const T=await this.standardizeUserData(l,u,null,null,!0,p);c=T[0],h=T[1],y=c.concat(h)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){m=!0;const k=Math.floor(r[0].shape[0]*(1-s.validationSplit)),T=r[0].shape[0];c=ea(r,k,T),a=r,r=ea(r,0,k),h=ea(o,k,T),i=o,o=ea(o,0,k),y=c.concat(h)}else s.validationSteps!=null&&(m=!0);const b=r.concat(o).concat(d);this.checkTrainableWeightsConsistency();const w=this.makeTrainFunction(),x=this.getDedupedMetricsNames();let $,C;m?(this.makeTestFunction(),$=this.testFunction,C=x.slice().concat(x.map(k=>"val_"+k))):($=null,y=[],C=x.slice());const E=p1(s.callbacks,s.yieldEvery);return await this.fitLoop(w,b,x,p,s.epochs,s.verbose,E,$,y,s.shuffle,C,s.initialEpoch,null,null)}finally{this.isTraining=!1,Ln(r,e),Ln(o,t),Ln(a,e),Ln(i,t),Ln(c,l),Ln(h,u),d!=null&&be(d)}}async fitLoop(e,t,s,r,o,a,i,l,u,c,h,d,p,f){r==null&&(r=32),o==null&&(o=1),c==null&&(c=!0),d==null&&(d=0);let g=!1;if(l!=null&&u!=null&&(g=!0),f!=null&&(g=!0,p==null))throw new L("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const m=this.checkNumSamples(t,r,p,"steps_per_epoch");let y;m!=null&&(y=Hn(0,m)),a==null&&(a=1);const{callbackList:b,history:w}=f1(i,a,o,d,m,p,r,g,h);b.setModel(this),this.history=w,await b.onTrainBegin(),this.stopTraining_=!1;for(let x=d;x{const T=E[A][0],S=E[A][1],_=Ar(C,T,S-T);k.batch=A,k.size=S-T;const P=gd(t,_),V=e(P);for(let M=0;Mgs(t))}else{const t=Object.keys(this.loss);e={};const s=this.loss;for(const r of t)if(typeof s[r]=="string")e[r]=gs(s[r]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[gs(al(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>gs(al(e)));{const e={};for(const t in this.metrics)e[t]=gs(al(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Ca(e.optimizer_config),s=Wn(t);let r;if(typeof e.loss=="string")r=$r(e.loss);else if(Array.isArray(e.loss))r=e.loss.map(a=>$r(a));else if(e.loss!=null){r={};for(const a in e.loss)r[a]=$r(e.loss[a])}let o;if(Array.isArray(e.metrics))o=e.metrics.map(a=>$r(a));else if(e.metrics!=null){o={};for(const a in e.metrics)o[a]=$r(e.metrics[a])}this.compile({loss:r,metrics:o,optimizer:s})}async save(e,t){if(typeof e=="string"){const u=Bx(e);if(u.length===0)throw new L(`Cannot find any save handlers for URL '${e}'`);if(u.length>1)throw new L(`Found more than one (${u.length}) save handlers for URL '${e}'`);e=u[0]}if(e.save==null)throw new L("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await Zh(this.getNamedWeights(t)),i={modelTopology:this.toJSON(null,!1),format:QF,generatedBy:`TensorFlow.js tfjs-layers v${Om}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){i.trainingConfig=this.getTrainingConfig();const u="optimizer",{data:c,specs:h}=await Zh(await this.optimizer.getWeights(),u);s.specs.push(...h),s.data=zx([s.data,c])}return this.userDefinedMetadata!=null&&(lb(this.userDefinedMetadata,this.name,!0),i.userDefinedMetadata=this.userDefinedMetadata),i.weightData=s.data,i.weightSpecs=s.specs,e.save(i)}setUserDefinedMetadata(e){lb(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}Xs.className="Model";Z(Xs);class N1 extends Xs{}N1.className="Functional";Z(N1);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */async function eL(n,e){"modelTopology"in n||(n={modelTopology:n}),n=n;let t=n.modelTopology;t.model_config!=null&&(t=t.model_config);const s=Ca(t),r=Wn(s,e);if(n.weightsManifest!=null){const o=await c0(n.weightsManifest,n.pathPrefix,r.weights.map(i=>i.originalName)),a={};for(const i of r.weights)a[i.originalName]=o[i.originalName];r.loadWeights(a),be(o)}return r}async function MJ(n,e){if(e==null&&(e={}),typeof n=="string"){const t=Vx(n,e);if(t.length===0)t.push(p0(n,e));else if(t.length>1)throw new L(`Found more than one (${t.length}) load handlers for URL '${n}'`);n=t[0]}return tL(n,void 0,e)}async function tL(n,e,t){if(t==null&&(t={}),n.load==null)throw new L("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const s=await n.load();let r=s.modelTopology;r.model_config!=null&&(r=r.model_config);const o=t.strict==null?!0:t.strict,a=s.weightData!=null&&s.weightSpecs!=null&&o,i=Wn(Ca(r),e,a),l=s.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),s.userDefinedMetadata!=null&&i.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new L("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:u,optimizerWeights:c}=nL(s.weightData,s.weightSpecs);i.loadWeights(u,o),i.optimizer!=null&&c.length>0&&await i.optimizer.setWeights(c),be(u),be(c.map(h=>h.tensor))}return i}function nL(n,e){const t=ef(n,e),s={},r=[];return e.forEach(o=>{o.group==="optimizer"?r.push({name:o.name,tensor:t[o.name]}):s[o.name]=t[o.name]}),{modelWeights:s,optimizerWeights:r}}class Co extends Xs{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:qc("sequential_"),e.layers!=null)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(s=>s<0))throw new L(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Co||e instanceof Xs;let s;if(t){if(s=e,s.outputs.length!==1)throw new L("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(s.inputs.length!==1)throw new L("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new L("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const r=h1({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(r)}if(t)this.outputs=s.outputs,this.inputs=s.inputs;else{if(e.inboundNodes.length!==1)throw new L(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new L("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=c1(this.outputs[0])}this.inboundNodes=[],new nh({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Br(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(r=>r.shape),outputShapes:this.outputs[0].shape})}else{const r=e.apply(this.outputs[0]);if(Array.isArray(r))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[r],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(De(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Xs({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,s=console.log){this.built||this.build(),super.summary(e,t,s)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,s={}){if(!this.built)throw new Tn("The model needs to be compiled before being used.");return this.model.evaluate(e,t,s)}async evaluateDataset(e,t){if(!this.built)throw new Tn("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,s={}){if(!this.built)throw new Tn("The model needs to be compiled before being used.");return this.model.fit(e,t,s)}async fitDataset(e,t){if(!this.built)throw new Tn("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,s={},r=!1){let o,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new L("Legacy serialization format not supported yet.");o=t}else I(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),o=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof Co))throw new xe(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const l of o){const c=Wn(l,void 0,r);r&&c.setFastWeightInitDuringBuild(!0),i.add(c)}return i}set stopTraining(e){if(this.model==null)throw new L("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new L("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const s={};s.className=t.getClassName(),s.config=t.getConfig(),e.push(s)}return{name:this.name,layers:e}}}Co.className="Sequential";Z(Co);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function BJ(n){return new Xs(n)}function VJ(n){return new Co(n)}function sL(n){return h1(n)}function WJ(n,e){pn.registerCallbackConstructor(n,e)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */let zt=class extends Qr{getConfig(){return{}}};class C1 extends zt{apply(e,t=1){return $_(e,t)}}C1.className="elu";Z(C1);class k1 extends zt{apply(e){return Cf(e)}}k1.className="selu";Z(k1);class T1 extends zt{apply(e){return hs(e)}}T1.className="relu";Z(T1);class E1 extends zt{apply(e){return z(()=>zr(6,hs(e)))}}E1.className="relu6";Z(E1);class A1 extends zt{apply(e){return e}}A1.className="linear";Z(A1);class R1 extends zt{apply(e){return ss(e)}}R1.className="sigmoid";Z(R1);class D1 extends zt{apply(e){return I_(e)}}D1.className="hardSigmoid";Z(D1);class O1 extends zt{apply(e){return Oo(e)}}O1.className="softplus";Z(O1);class _1 extends zt{apply(e){return S_(e)}}_1.className="softsign";Z(_1);class F1 extends zt{apply(e){return Lr(e)}}F1.className="tanh";Z(F1);let _m=class extends zt{apply(e,t=-1){return Ac(e,t)}};_m.className="softmax";Z(_m);class L1 extends zt{apply(e,t=-1){return gf(e,t)}}L1.className="logSoftmax";Z(L1);class P1 extends zt{apply(e){return z(()=>z(()=>{const t=Math.sqrt(2),s=O(.5,Y(1,pf(ce(e,t))));return O(e,s)}))}}P1.className="gelu";Z(P1);class z1 extends zt{apply(e){return z(()=>O(.5,O(e,Y(1,Lr(O(At(ce(2,Math.PI)),Y(e,O(.044715,Ns(e,3)))))))))}}z1.className="gelu_new";Z(z1);class M1 extends zt{apply(e){return z(()=>O(e,Lr(Oo(e))))}}M1.className="mish";Z(M1);class B1 extends zt{apply(e,t=1){return z(()=>O(ss(O(e,t)),e))}}B1.className="swish";Z(B1);function sr(n){return n.getClassName()}function Fh(n,e={}){return Bi(n,mn.getMap().classNameMap,e,"activation")}function rr(n){if(n==null){const e={};return e.className="linear",e.config={},Fh(e)}if(typeof n=="string"){const e={};return e.className=n,e.config={},Fh(e)}else return n instanceof zt?n:Fh(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Fm(n){if(n!=null&&typeof n!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`)}class V1 extends Qr{}class Hi extends V1{constructor(e){super(),Fm(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return z(()=>{let t=ct([1]);return this.hasL1&&(t=Y(t,ie(O(this.l1,lt(e))))),this.hasL2&&(t=Y(t,ie(O(this.l2,Wi(e))))),F(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Hi.className="L1L2";Z(Hi);function rL(n){return Fm(n),new Hi({l1:n!=null?n.l1:null,l2:0})}function oL(n){return Fm(n),new Hi({l2:n!=null?n.l2:null,l1:0})}const fb={l1l2:"L1L2"};function Me(n){return pm(n)}function mb(n,e={}){return Bi(n,mn.getMap().classNameMap,e,"regularizer")}function qe(n){if(n==null)return null;if(typeof n=="string"){const t={className:n in fb?fb[n]:n,config:{}};return mb(t)}else return n instanceof V1?n:mb(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Lm extends Ie{constructor(e){super(e??{}),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=ge(e);let s=hs(e);return this.maxValue!=null&&(s=ln(s,0,this.maxValue)),s}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Lm.className="ReLU";Z(Lm);class Pm extends Ie{constructor(e){super(e??{}),this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const s=ge(e);return xc(s,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Pm.className="LeakyReLU";Z(Pm);class zm extends Ie{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=je(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=qe(e.alphaRegularizer),this.alphaConstraint=mt(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new L(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=De(e);const t=e.slice(1);if(this.sharedAxes!=null)for(const r of this.sharedAxes)t[r-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const s={};if(this.sharedAxes!=null)for(let r=1;r{let s=ge(e);const r=t.mask;if(r!=null){const o=O(ae(rn(s.shape),ee(r,s.dtype)),pe(-1e9));s=Y(s,o)}return this.axis instanceof Array?this.axis.length>1?un(ae(s,$c(s,this.axis,!0))):this.softmax(s,this.axis[0]):this.softmax(s,this.axis)})}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}Vm.className="Softmax";Z(Vm);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function bo(n,e,t){if(typeof n=="number")return Br(n,e);if(n.length!==e)throw new L(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${n.length} elements.`);for(let s=0;s(rt(e),e==="channelsFirst"?ke(n,[0,2,3,1]):n))}function W1(n,e){return z(()=>(rt(e),e==="channelsFirst"?ke(n,[0,2,3,4,1]):n))}function aL(n,e,t,s=1,r="valid",o,a=1){return z(()=>{if(o==null&&(o=jn()),rt(o),n.shape.length!==3)throw new L(`The input of a conv1dWithBias operation should be 3, but is ${n.shape.length} instead.`);if(e.shape.length!==3)throw new L(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);if(t!=null&&t.shape.length!==1)throw new L(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(o==="channelsFirst"&&(n=ke(n,[0,2,1])),r==="causal")throw new xe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=lf(n,e,s,r==="same"?"same":"valid","NWC",a);return t!=null&&(i=Xn(i,t)),i})}function gb(n,e,t,s=[1,1],r="valid",o,a,i=null){return z(()=>{if(o==null&&(o=jn()),rt(o),n.rank!==3&&n.rank!==4)throw new L(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);if(e.rank!==3&&e.rank!==4)throw new L(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);let l=Wm(n,o);if(r==="causal")throw new xe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Xw({x:l,filter:e,strides:s,pad:r==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:t,activation:i}),o==="channelsFirst"&&(l=ke(l,[0,3,1,2])),l})}function iL(n,e,t,s=[1,1,1],r="valid",o,a){return z(()=>{if(o==null&&(o=jn()),rt(o),n.rank!==4&&n.rank!==5)throw new L(`conv3dWithBias expects input to be of rank 4 or 5, but received ${n.rank}.`);if(e.rank!==4&&e.rank!==5)throw new L(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${n.rank}.`);let i=W1(n,o);if(r==="causal")throw new xe("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=fw(i,e,s,r==="same"?"same":"valid","NDHWC",a),t!=null&&(i=Xn(i,t)),o==="channelsFirst"&&(i=ke(i,[0,4,1,2,3])),i})}class oh extends Ie{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",oh.verifyArgs(t),this.rank=e,xt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new xe(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=bo(t.kernelSize,e,"kernelSize"),this.strides=bo(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Sn(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,rt(this.dataFormat),this.activation=rr(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=je(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=mt(t.biasConstraint),this.biasRegularizer=qe(t.biasRegularizer),this.activityRegularizer=qe(t.activityRegularizer),this.dilationRate=bo(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new L(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new L(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new L(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Jn("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!fm(e.kernelSize,"number",1,3))throw new L(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:sr(this.activation),useBias:this.useBias,biasInitializer:Ye(this.biasInitializer),biasRegularizer:Me(this.biasRegularizer),activityRegularizer:Me(this.activityRegularizer),biasConstraint:ft(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Mo extends oh{constructor(e,t){super(e,t),this.kernel=null,Mo.verifyArgs(t),this.filters=t.filters,xt(this.filters,"filters"),this.kernelInitializer=je(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=mt(t.kernelConstraint),this.kernelRegularizer=qe(t.kernelRegularizer)}build(e){e=De(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new L(`The channel dimension of the input should be defined. Found ${e[t]}`);const s=e[t],r=this.kernelSize.concat([s,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:s}}],this.built=!0}call(e,t){return z(()=>{e=ge(e);let s;const r=this.bias==null?null:this.bias.read(),o=n1(this.activation.getClassName());if(o!=null&&this.rank===2)s=gb(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate,o);else{if(this.rank===1)s=aL(e,this.kernel.read(),r,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=gb(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=iL(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new xe("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(s=this.activation.apply(s))}return s})}computeOutputShape(e){e=De(e);const t=[],s=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let o=0;o 0 but got ${JSON.stringify(e.filters)}`)}}class Bo extends Mo{constructor(e){super(2,e),Bo.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!fm(e.kernelSize,"number",1,2))throw new L(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Bo.className="Conv2D";Z(Bo);class Vo extends Mo{constructor(e){super(3,e),Vo.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new L(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Vo.className="Conv3D";Z(Vo);class Um extends Bo{constructor(e){if(super(e),this.inputSpec=[new dt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new L(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=De(e),e.length!==4)throw new L("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new L("The channel dimension of the inputs should be defined. Found `None`.");const s=e[t],r=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new dt({ndim:4,axes:{[t]:s}})],this.built=!0}call(e,t){return z(()=>{let s=ge(e);if(s.shape.length!==4)throw new L(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const r=s.shape,o=r[0];let a,i;this.dataFormat==="channelsFirst"?(a=2,i=3):(a=1,i=2);const l=r[a],u=r[i],c=this.kernelSize[0],h=this.kernelSize[1],d=this.strides[0],p=this.strides[1],f=Qn(l,d,c,this.padding),g=Qn(u,p,h,this.padding),m=[o,f,g,this.filters];this.dataFormat!=="channelsLast"&&(s=ke(s,[0,2,3,1]));let y=cf(s,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(y=ke(y,[0,3,1,2])),this.bias!=null&&(y=Xn(y,this.bias.read(),this.dataFormat)),this.activation!=null&&(y=this.activation.apply(y)),y})}computeOutputShape(e){e=De(e);const t=e.slice();let s,r,o;this.dataFormat==="channelsFirst"?(s=1,r=2,o=3):(s=3,r=1,o=2);const a=this.kernelSize[0],i=this.kernelSize[1],l=this.strides[0],u=this.strides[1];return t[s]=this.filters,t[r]=Qn(t[r],l,a,this.padding),t[o]=Qn(t[o],u,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Um.className="Conv2DTranspose";Z(Um);class Gm extends Vo{constructor(e){if(super(e),this.inputSpec=[new dt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new L(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=De(e),e.length!==5)throw new L("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new L("The channel dimension of the inputs should be defined. Found `None`.");const s=e[t],r=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new dt({ndim:5,axes:{[t]:s}})],this.built=!0}call(e,t){return z(()=>{let s=ge(e);if(s.shape.length!==5)throw new L(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const r=s.shape,o=r[0];let a,i,l;this.dataFormat==="channelsFirst"?(l=2,a=3,i=4):(l=1,a=2,i=3);const u=r[l],c=r[a],h=r[i],d=this.kernelSize[0],p=this.kernelSize[1],f=this.kernelSize[2],g=this.strides[0],m=this.strides[1],y=this.strides[2],b=Qn(u,g,d,this.padding),w=Qn(c,m,p,this.padding),x=Qn(h,y,f,this.padding),$=[o,b,w,x,this.filters];this.dataFormat!=="channelsLast"&&(s=ke(s,[0,2,3,4,1]));let C=gw(s,this.kernel.read(),$,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(C=ke(C,[0,4,1,2,3])),this.bias!==null&&(C=Xn(C,this.bias.read(),this.dataFormat)),this.activation!==null&&(C=this.activation.apply(C)),C})}computeOutputShape(e){e=De(e);const t=e.slice();let s,r,o,a;this.dataFormat==="channelsFirst"?(s=1,r=2,o=3,a=4):(s=4,r=1,o=2,a=3);const i=this.kernelSize[0],l=this.kernelSize[1],u=this.kernelSize[2],c=this.strides[0],h=this.strides[1],d=this.strides[2];return t[s]=this.filters,t[r]=Qn(t[r],c,i,this.padding),t[o]=Qn(t[o],h,l,this.padding),t[a]=Qn(t[a],d,u,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Gm.className="Conv3DTranspose";Z(Gm);class U1 extends Mo{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new L("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new L("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new L(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=je(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=qe(t.depthwiseRegularizer),this.depthwiseConstraint=mt(t.depthwiseConstraint),this.pointwiseInitializer=je(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=qe(t.pointwiseRegularizer),this.pointwiseConstraint=mt(t.pointwiseConstraint)}build(e){if(e=De(e),e.length{e=ge(e);let s;if(this.rank===1)throw new xe("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=ke(e,[0,2,3,1])),s=kf(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=Xn(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),this.dataFormat==="channelsFirst"&&(s=ke(s,[0,3,1,2])),s})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ye(this.depthwiseInitializer),e.pointwiseInitializer=Ye(this.pointwiseInitializer),e.depthwiseRegularizer=Me(this.depthwiseRegularizer),e.pointwiseRegularizer=Me(this.pointwiseRegularizer),e.depthwiseConstraint=ft(this.depthwiseConstraint),e.pointwiseConstraint=ft(this.pointwiseConstraint),e}}U1.className="SeparableConv";class Hm extends U1{constructor(e){super(2,e)}}Hm.className="SeparableConv2D";Z(Hm);class ji extends Mo{constructor(e){super(1,e),ji.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!fm(e.kernelSize,"number",1,1))throw new L(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}ji.className="Conv1D";Z(ji);class jm extends Ie{constructor(e){super(e),typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return z(()=>{if(e=ge(e),this.dataFormat==="channelsLast"){const s=ol(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return ol(s,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=ol(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return ol(s,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}jm.className="Cropping2D";Z(jm);class qm extends Ie{constructor(e){super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,rt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,m_(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){const t=e[2]==null?null:this.size[0]*e[2],s=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,s]}else{const t=e[1]==null?null:this.size[0]*e[1],s=e[2]==null?null:this.size[1]*e[2];return[e[0],t,s,e[3]]}}call(e,t){return z(()=>{let s=ge(e);const r=s.shape;if(this.dataFormat==="channelsFirst"){s=ke(s,[0,2,3,1]);const o=this.size[0]*r[2],a=this.size[1]*r[3],i=this.interpolation==="nearest"?Bn.resizeNearestNeighbor(s,[o,a]):Bn.resizeBilinear(s,[o,a]);return ke(i,[0,3,1,2])}else{const o=this.size[0]*r[1],a=this.size[1]*r[2];return this.interpolation==="nearest"?Bn.resizeNearestNeighbor(s,[o,a]):Bn.resizeBilinear(s,[o,a])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}qm.className="UpSampling2D";Z(qm);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function lL(n,e,t=[1,1],s="valid",r,o){return z(()=>{r==null&&(r=jn()),rt(r);let a=Wm(n,r);if(n.rank!==4)throw new L(`Input for depthwiseConv2d is required to be 4-D, but is instead ${n.rank}-D`);if(e.rank!==4)throw new L(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);return a=Di(a,e,t,s==="same"?"same":"valid","NHWC",o),r==="channelsFirst"&&(a=ke(a,[0,3,1,2])),a})}class Km extends oh{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=je(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=mt(e.depthwiseConstraint),this.depthwiseRegularizer=qe(e.depthwiseRegularizer)}build(e){if(e=De(e),e.length<4)throw new L(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new L(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const s=e[t],r=[this.kernelSize[0],this.kernelSize[1],s,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[s*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return z(()=>{e=ge(e);let s=lL(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=Xn(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),s})}computeOutputShape(e){e=De(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,o=Un(t,this.kernelSize[0],this.padding,this.strides[0]),a=Un(s,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],r,o,a]:[e[0],o,a,r]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ye(this.depthwiseInitializer),e.depthwiseRegularizer=Me(this.depthwiseRegularizer),e.depthwiseConstraint=ft(this.depthwiseRegularizer),e}}Km.className="DepthwiseConv2D";Z(Km);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function G1(n,e,t,s){if(Array.isArray(n)){if(e!=null||t!=null)throw new L("When inputs is an array, neither initialState or constants should be provided");s!=null&&(t=n.slice(n.length-s,n.length),n=n.slice(0,n.length-s)),n.length>1&&(e=n.slice(1,n.length)),n=n[0]}function r(o){return o==null||Array.isArray(o)?o:[o]}return e=r(e),t=r(t),{inputs:n,initialState:e,constants:t}}function H1(n,e,t,s=!1,r,o,a=!1,i=!1){return z(()=>{const l=e.shape.length;if(l<3)throw new L(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(Hn(2,l));e=ke(e,u),a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=ee(ee(r,"bool"),"float32"),r.rank===l-1&&(r=Lt(r,-1)),r=ke(r,u)),s&&(e=An(e,0),r!=null&&(r=An(r,0)));const c=[];let h,d=t;const p=e.shape[0],f=Rn(e);let g;r!=null&&(g=Rn(r));for(let y=0;yn(b,d));if(r==null)h=w[0],d=w[1];else{const x=z(()=>{const $=g[y],C=ae($n($),$),E=Y(O(w[0],$),O(d[0],C)),A=d.map((k,T)=>Y(O(w[1][T],$),O(k,C)));return{output:E,newStates:A}});h=x.output,d=x.newStates}i&&c.push(h)}let m;return i&&(m=Xt(c,1)),[h,m,d]})}class ds extends Ie{constructor(e){super(e);let t;if(e.cell==null)throw new L("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new lh({cells:e.cell}):t=e.cell,t.stateSize==null)throw new L("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new dt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Hn(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){dd(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const s=t[0];let r;if(this.returnSequences?r=[e[0],e[1],s]:r=[e[0],s],this.returnState){const o=[];for(const a of t)o.push([e[0],a]);return[r].concat(o)}else return r}computeMask(e,t){return z(()=>{Array.isArray(t)&&(t=t[0]);const s=this.returnSequences?t:null;if(this.returnState){const r=this.states.map(o=>null);return[s].concat(r)}else return s})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let s=0;sa.shape[a.shape.length-1]),o))throw new L(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=o.map(a=>new dt({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){z(()=>{if(!this.stateful)throw new Zn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new L("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>ct([s,r])):this.states_=[ct([s,this.cell.stateSize])];else if(e==null)be(this.states_),this.keptStates!=null&&(be(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>ct([s,r])):this.states_[0]=ct([s,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new L(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):be(this.states_);for(let r=0;rbt(r.clone()))})}apply(e,t){let s=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});const o=G1(e,s,r,this.numConstants);e=o.inputs,s=o.initialState,r=o.constants;let a=[],i=[];if(s!=null){t.initialState=s,a=a.concat(s),this.stateSpec=[];for(const u of s)this.stateSpec.push(new dt({shape:u.shape}));i=i.concat(this.stateSpec)}if(r!=null&&(t.constants=r,a=a.concat(r),this.numConstants=r.length),a[0]instanceof us){const u=[e].concat(a),c=this.inputSpec.concat(i),h=this.inputSpec;this.inputSpec=c;const d=super.apply(u,t);return this.inputSpec=h,d}else return super.apply(e,t)}call(e,t){return z(()=>{const s=t==null?null:t.mask,r=t==null?null:t.training;let o=t==null?null:t.initialState;e=ge(e),o==null&&(this.stateful?o=this.states_:o=this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(o.length!==a)throw new L(`RNN Layer has ${a} state(s) but was passed ${o.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:r},u=H1((f,g)=>{const m=this.cell.call([f].concat(g),i);return[m[0],m.slice(1)]},e,o,this.goBackwards,s,null,this.unroll,this.returnSequences),c=u[0],h=u[1],d=u[2];this.stateful&&this.resetStates(d,r);const p=this.returnSequences?h:c;return this.returnState?[p].concat(d):p})}getInitialState(e){return z(()=>{let t=ct(e.shape);return t=ie(t,[1,2]),t=Vi(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?cd(t,[1,s]):t):this.cell.stateSize>1?[cd(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);const s=this.cell.getConfig();return this.getClassName()===ds.className&&(t.cell={className:this.cell.getClassName(),config:s}),Object.assign(Object.assign(Object.assign({},s),e),t)}static fromConfig(e,t,s={}){const r=t.cell,o=Wn(r,s);return new e(Object.assign(t,{cell:o}))}}ds.className="RNN";Z(ds);class qi extends Ie{}class ah extends qi{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xt(this.units,"units"),this.activation=rr(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=je(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=qe(e.kernelRegularizer),this.recurrentRegularizer=qe(e.recurrentRegularizer),this.biasRegularizer=qe(e.biasRegularizer),this.kernelConstraint=mt(e.kernelConstraint),this.recurrentConstraint=mt(e.recurrentConstraint),this.biasConstraint=mt(e.biasConstraint),this.dropout=Io([1,nr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Io([1,nr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=De(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return z(()=>{if(e=e,e.length!==2)throw new L(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let s=e[1];e=e[0];const r=t.training==null?!1:t.training;0$n(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0$n(s),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));let o;const a=this.dropoutMask,i=this.recurrentDropoutMask;a!=null?o=as(O(e,a),this.kernel.read()):o=as(e,this.kernel.read()),this.bias!=null&&(o=Xn(o,this.bias.read())),i!=null&&(s=O(s,i));let l=Y(o,as(s,this.recurrentKernel.read()));return this.activation!=null&&(l=this.activation.apply(l)),[l,l]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:sr(this.activation),useBias:this.useBias,kernelInitializer:Ye(this.kernelInitializer),recurrentInitializer:Ye(this.recurrentInitializer),biasInitializer:Ye(this.biasInitializer),kernelRegularizer:Me(this.kernelRegularizer),recurrentRegularizer:Me(this.recurrentRegularizer),biasRegularizer:Me(this.biasRegularizer),activityRegularizer:Me(this.activityRegularizer),kernelConstraint:ft(this.kernelConstraint),recurrentConstraint:ft(this.recurrentConstraint),biasConstraint:ft(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}ah.className="SimpleRNNCell";Z(ah);class Xm extends ds{constructor(e){e.cell=new ah(e),super(e)}call(e,t){return z(()=>{this.cell.dropoutMask!=null&&(be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,r=t==null?null:t.training,o=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:o})})}static fromConfig(e,t){return new e(t)}}Xm.className="SimpleRNN";Z(Xm);class ih extends qi{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new L("GRUCell does not support reset_after parameter set to true.");this.units=e.units,xt(this.units,"units"),this.activation=rr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=rr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=je(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=qe(e.kernelRegularizer),this.recurrentRegularizer=qe(e.recurrentRegularizer),this.biasRegularizer=qe(e.biasRegularizer),this.kernelConstraint=mt(e.kernelConstraint),this.recurrentConstraint=mt(e.recurrentConstraint),this.biasConstraint=mt(e.biasConstraint),this.dropout=Io([1,nr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Io([1,nr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=De(e);const t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return z(()=>{if(e=e,e.length!==2)throw new L(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training==null?!1:t.training;let r=e[1];e=e[0],0$n(e),rate:this.dropout,training:s,count:3,dropoutFunc:this.dropoutFunc})),0$n(r),rate:this.recurrentDropout,training:s,count:3,dropoutFunc:this.dropoutFunc}));const o=this.dropoutMask,a=this.recurrentDropoutMask;let i,l,u;0{this.cell.dropoutMask!=null&&(be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,r=t==null?null:t.training,o=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:o})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Ym.className="GRU";Z(Ym);class Ki extends qi{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xt(this.units,"units"),this.activation=rr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=rr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=je(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=qe(e.kernelRegularizer),this.recurrentRegularizer=qe(e.recurrentRegularizer),this.biasRegularizer=qe(e.biasRegularizer),this.kernelConstraint=mt(e.kernelConstraint),this.recurrentConstraint=mt(e.recurrentConstraint),this.biasConstraint=mt(e.biasConstraint),this.dropout=Io([1,nr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Io([1,nr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=De(e);const s=e[e.length-1];this.kernel=this.addWeight("kernel",[s,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let r;if(this.useBias){if(this.unitForgetBias){const o=this.biasInitializer,a=this.units;r=new(t=class extends On{apply(l,u){const c=o.apply([a]),h=new Xc().apply([a]),d=o.apply([a*2]);return Qy(Qy(c,h),d)}},t.className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return z(()=>{const s=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new L(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1];const o=e[2];e=e[0],0$n(e),rate:this.dropout,training:s,count:4,dropoutFunc:this.dropoutFunc})),0$n(r),rate:this.recurrentDropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let l,u,c,h;0{this.cell.dropoutMask!=null&&(be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,r=t==null?null:t.training,o=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:o})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Zm.className="LSTM";Z(Zm);class lh extends qi{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return z(()=>{e=e;let s=e.slice(1);const r=[];for(const i of this.cells.slice().reverse())Array.isArray(i.stateSize)?r.push(s.splice(0,i.stateSize.length)):r.push(s.splice(0,1));r.reverse();const o=[];let a;for(let i=0;i{Er(`RNNCell_${r}`,()=>{s.build(e),Array.isArray(s.stateSize)?t=s.stateSize[0]:t=s.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t=o=>({className:o.getClassName(),config:o.getConfig()}),r={cells:this.cells.map(t)};return Object.assign(Object.assign({},e),r)}static fromConfig(e,t,s={}){const r=[];for(const o of t.cells)r.push(Wn(o,s));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const s of this.cells)t.push(...s.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return pd(e)}setWeights(e){const t=[];for(const s of this.cells){const r=s.weights.length,o=e.splice(r);for(let a=0;ao!=null?o(e(),t):u1(e(),t),i=()=>Ui(a,e,s);return!r||r<=1?bt(i().clone()):Array(r).fill(void 0).map(i).map(u=>bt(u.clone()))}/** + * @license + * Copyright 2020 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */var uL=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r{if(this.cell.dropoutMask!=null&&(be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new L("ConvRNN2D cell does not support constants");const s=t==null?null:t.mask,r=t==null?null:t.training,o=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:o})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return z(()=>{const{stateSize:t}=this.cell,s=e.shape,r=this.computeSingleOutputShape(s),o=[r[0],...r.slice(2)],a=ct(o);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){z(()=>{if(!this.stateful)throw new Zn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape,r=this.computeSingleOutputShape(s),o=[r[0],...r.slice(2)];if(s[0]==null)throw new L("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ct(o)):this.states_=[ct(o)];else if(e==null)be(this.states_),this.keptStates!=null&&(be(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ct(o)):this.states_[0]=ct(o);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new L(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):be(this.states_);for(let i=0;ibt(i.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:s,kernelSize:r,padding:o,strides:a,dilationRate:i}=this.cell,l=t==="channelsFirst",u=e[l?3:2],c=e[l?4:3],h=Un(u,r[0],o,a[0],i[0]),d=Un(c,r[1],o,a[1],i[1]);return[...e.slice(0,2),...l?[s,h,d]:[h,d,s]]}}j1.className="ConvRNN2D";class uh extends Ki{constructor(e){const{filters:t,kernelSize:s,strides:r,padding:o,dataFormat:a,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,xt(this.filters,"filters"),this.kernelSize=bo(s,2,"kernelSize"),this.kernelSize.forEach(l=>xt(l,"kernelSize")),this.strides=bo(r||1,2,"strides"),this.strides.forEach(l=>xt(l,"strides")),this.padding=o||"valid",Sn(this.padding),this.dataFormat=a||"channelsLast",rt(this.dataFormat),this.dilationRate=bo(i||1,2,"dilationRate"),this.dilationRate.forEach(l=>xt(l,"dilationRate"))}build(e){var t;e=De(e);const s=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[s]==null)throw new L(`The channel dimension of the input should be defined. Found ${e[s]}`);const r=e[s],o=4,a=this.kernelSize.concat([r,this.filters*o]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const i=this.kernelSize.concat([this.filters,this.filters*o]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let l;if(this.unitForgetBias){const u=this.biasInitializer,c=this.filters;l=new(t=class extends On{apply(d,p){const f=u.apply([c]),g=rn([c]),m=u.apply([c*2]);return mm([f,g,m])}},t.className="CustomInit",t)}else l=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*o],null,l,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return z(()=>{if(e.length!==3)throw new L(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training||!1,r=e[0],o=e[1],a=e[2],i=4;0$n(r),rate:this.dropout,training:s,count:i,dropoutFunc:this.dropoutFunc}));const l=this.dropoutMask,u=(K,X,J)=>!X||!X[J]?K:O(X[J],K);let c=u(r,l,0),h=u(r,l,1),d=u(r,l,2),p=u(r,l,3);0$n(o),rate:this.recurrentDropout,training:s,count:i,dropoutFunc:this.dropoutFunc}));const f=this.recurrentDropoutMask;let g=u(o,f,0),m=u(o,f,1),y=u(o,f,2),b=u(o,f,3);const w=3,[x,$,C,E]=on(this.kernel.read(),i,w),[A,k,T,S]=this.useBias?on(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,x,A,this.padding),h=this.inputConv(h,$,k,this.padding),d=this.inputConv(d,C,T,this.padding),p=this.inputConv(p,E,S,this.padding);const[_,P,V,M]=on(this.recurrentKernel.read(),i,w);g=this.recurrentConv(g,_),m=this.recurrentConv(m,P),y=this.recurrentConv(y,V),b=this.recurrentConv(b,M);const W=this.recurrentActivation.apply(Y(c,g)),j=this.recurrentActivation.apply(Y(h,m)),U=Y(O(j,a),O(W,this.activation.apply(Y(d,y)))),q=O(this.recurrentActivation.apply(Y(p,b)),this.activation.apply(U));return[q,q,U]})}getConfig(){const e=super.getConfig(),{units:t}=e,s=uL(e,["units"]),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},s),r)}inputConv(e,t,s,r){const o=tr(e,t,this.strides,r||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return s?Xn(o,s,this.dataFormat):o}recurrentConv(e,t){return tr(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}uh.className="ConvLSTM2DCell";Z(uh);class Jm extends j1{constructor(e){const t=new uh(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}Jm.className="ConvLSTM2D";Z(Jm);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class ch extends Ie{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;const t=e.shape,s=[];for(let r=0;r{this.invokeCallHook(e,t);const s=ge(e);if(0u1(s,this.rate,o,this.seed),()=>s,r)}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}ch.className="Dropout";Z(ch);class Qm extends ch{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Qm.className="SpatialDropout1D";Z(Qm);class eg extends Ie{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,xt(this.units,"units"),this.activation=rr(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=mt(e.kernelConstraint),this.biasConstraint=mt(e.biasConstraint),this.kernelRegularizer=qe(e.kernelRegularizer),this.biasRegularizer=qe(e.biasRegularizer),this.activityRegularizer=qe(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=De(e);const t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=De(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return z(()=>{this.invokeCallHook(e,t);const s=ge(e),r=n1(this.activation.getClassName());let o;return r!=null?o=as(s,this.kernel.read(),r,this.bias?this.bias.read():null):(o=as(s,this.kernel.read()),this.bias!=null&&(o=Xn(o,this.bias.read())),this.activation!=null&&(o=this.activation.apply(o))),o})}getConfig(){const e={units:this.units,activation:sr(this.activation),useBias:this.useBias,kernelInitializer:Ye(this.kernelInitializer),biasInitializer:Ye(this.biasInitializer),kernelRegularizer:Me(this.kernelRegularizer),biasRegularizer:Me(this.biasRegularizer),activityRegularizer:Me(this.activityRegularizer),kernelConstraint:ft(this.kernelConstraint),biasConstraint:ft(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}eg.className="Dense";Z(eg);class tg extends Ie{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=De(e);for(const t of e.slice(1))if(t==null)throw new L(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Ks(e,1)]}call(e,t){return z(()=>{this.invokeCallHook(e,t);let s=ge(e);if(this.dataFormat==="channelsFirst"&&s.rank>1){const r=[0];for(let o=2;o{this.invokeCallHook(e,t);const s=ge(e);return this.activation.apply(s)})}getConfig(){const e={activation:sr(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}ng.className="Activation";Z(ng);class sg extends Ie{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return z(()=>(e=ge(e),x_(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}sg.className="RepeatVector";Z(sg);class rg extends Ie{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);const s=ge(e),r=s.shape,o=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return F(s,o)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}rg.className="Reshape";Z(rg);class og extends Ie{constructor(e){if(super(e),e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=Hn(1,e.dims.length+1);if(!Ce(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new dt({ndim:this.dims.length+1})]}computeOutputShape(e){e=De(e);const t=e.slice();return this.dims.forEach((s,r)=>{t[r+1]=e[s]}),t}call(e,t){return ke(ge(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}og.className="Permute";Z(og);class ag extends Ie{constructor(e){super(e??{}),this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const s=ge(e);return Bl($o(s,this.maskValue),-1)}call(e,t){return z(()=>{this.invokeCallHook(e,t);const s=ge(e),a=Bl($o(s,this.maskValue),-1,!0);return O(s,ee(a,s.dtype))})}}ag.className="Masking";Z(ag);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class ig extends Ie{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(_e(e.inputLength))}this.inputDim=e.inputDim,xt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,xt(this.outputDim,"outputDim"),this.embeddingsInitializer=je(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=qe(e.embeddingsRegularizer),this.activityRegularizer=qe(e.activityRegularizer),this.embeddingsConstraint=mt(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return z(()=>this.maskZero?(e=ge(e),$o(e,Ee(e))):null)}computeOutputShape(e){if(e=De(e),this.inputLength==null)return[...e,this.outputDim];const t=_e(this.inputLength);if(t.length!==e.length-1)throw new L(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let s=0;for(let r=0;r{this.invokeCallHook(e,t);let s=ge(e);s.dtype!=="int32"&&(s=os(s,"int32"));const r=l1(this.embeddings.read(),F(s,[s.size]));return F(r,De(this.computeOutputShape(s.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ye(this.embeddingsInitializer),embeddingsRegularizer:Me(this.embeddingsRegularizer),activityRegularizer:Me(this.activityRegularizer),embeddingsConstraint:ft(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}ig.className="Embedding";Z(ig);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class no extends Ie{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new xe}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new L(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let s=e[0]==null?null:e[0].slice(1);for(let o=1;oo.length);e.indexOf(null)===-1&&qs(r).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return z(()=>{if(e=e,this.reshapeRequired){const s=[],r=e.map(o=>o.rank);if(r.indexOf(null)===-1){const o=nr(r);for(let a of e){const i=a.rank;for(let l=0;l1){const c=Hn(1,u).concat([0]);s.push(ke(l,c)),o=!0}else s.push(l)}let a=this.mergeFunction(s);const i=a.rank;if(o){if(i==null){const l=a.shape,u=l.length,c=l[u-1],h=[c].concat(l.slice(0,l.length-1));a=F(ke(F(a,[-1,c]),[1,0]),h)}else if(i>1){const l=[i-1].concat(Hn(0,i-1));a=ke(a,l)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let r=1;r{if(t==null)return null;if(!Array.isArray(t))throw new L("`mask` should be an Array");if(!Array.isArray(e))throw new L("`inputs` should be an Array");if(t.length!==e.length)throw new L(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(r=>r==null))return null;t=t.map(r=>r==null?r:Lt(r,0));let s=t[0];for(let r=1;r{let t=e[0].clone();for(let s=1;s{let t=e[0].clone();for(let s=1;s{let t=e[0].clone();for(let s=1;s{let t=e[0];for(let s=1;s{let t=e[0];for(let s=1;s1)throw new L("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return z(()=>mm(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new L("A `Concatenate` layer should be called on a list of inputs.");const t=e,s=t[0].slice(),r=this.axis<0?s.length+this.axis:this.axis;for(const o of t.slice(1)){if(s[r]==null||o[r]==null){s[r]=null;break}s[r]+=o[r]}return s}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new L("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new L("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new L(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return z(()=>{let s=!0;if(t.forEach(a=>{if(a!=null){s=!1;return}}),s)return null;const r=[];for(let a=0;a3||e.shape.length>3)throw new xe("batchDot is not implemented for tensors of 4D or higher rank yet");if(I(n.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${n.shape.length}`),I(n.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${e.shape.length}`),typeof t=="number"&&(t=[t,t]),n.dtype==="complex64"||e.dtype==="complex64")throw new xe("batchDot is not implemented for complex64-type Tensors yet.");const s=n.shape.length,r=e.shape.length;t==null&&(t=[s-1,r-2]);const o=t;return z(()=>{let a;if(s>r){a=s-r;const l=[];for(let u=0;us){a=r-s;const l=[];for(let u=0;u0){let l;s>r?l=s+r-3:l=s-1;const u=[];for(let c=l;c"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],s=e[1];if(t.length>3||s.length>3)throw new xe("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,s);if(t[r[0]]!==s[r[1]])throw new L(`Dimension incompatibility: ${t[r[0]]} !== ${s[r[1]]}`)}mergeFunction(e){if(e.length!==2)throw new L(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],s=e[1],r;return Array.isArray(this.axes)?r=this.axes.map((o,a)=>ta(o,e[a].shape.length)):r=[ta(this.axes,t.shape.length),ta(this.axes,s.shape.length)],this.normalize&&(t=ql(t,r[0]),s=ql(s,r[1])),cL(t,s,r)}interpretAxes(e,t){let s;return Array.isArray(this.axes)?s=this.axes:s=[ta(this.axes,e.length),ta(this.axes,t.length)],s}computeOutputShape(e){I(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0].slice(),s=e[1].slice();if(t.length>3||s.length>3)throw new xe("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,s);t.splice(r[0],1),s.splice(r[1],1),s.splice(0,1);const o=t.concat(s);return o.length===1&&o.push(1),o}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}fg.className="Dot";Z(fg);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class mg extends Ie{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return z(()=>{this.invokeCallHook(e,t);const s=ge(e);return Ui(()=>Y(Kc(s.shape,0,this.stddev),s),()=>s,t.training||!1)})}}mg.className="GaussianNoise";Z(mg);class gg extends Ie{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return z(()=>{this.invokeCallHook(e,t);const s=ge(e);return this.rate>0&&this.rate<1?Ui(()=>{const o=Math.sqrt(this.rate/(1-this.rate));return O(s,Kc(s.shape,1,o))},()=>s,t.training||!1):s})}}gg.className="GaussianDropout";Z(gg);class yg extends Ie{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||ge(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return z(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(e);return Ui(()=>{const o=ge(e),i=-1.6732632423543772*1.0507009873554805;let l=hr(Zr(s),this.rate);l=os(l,"float32");const u=((1-this.rate)*(1+this.rate*i**2))**-.5,c=-u*i*this.rate,h=Y(O(o,l),O(Y(l,-1),i));return Y(O(h,u),c)},()=>ge(e),t.training||!1)}return e})}}yg.className="AlphaDropout";Z(yg);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function ka(n,e,t,s,r,o=.001){let a;if(n.rank===2)a=ow(n,e,t,s,r,o);else if(n.rank===3)a=aw(n,e,t,s,r,o);else if(n.rank===4)a=iw(n,e,t,s,r,o);else throw new xe(`batchNormalization is not implemented for array of rank ${n.rank} yet`);return a}function hL(n,e,t,s,r=.001){return z(()=>{const o=Nc(n,s),a=o.mean,i=o.variance;return[ka(n,a,i,t,e,r),a,i]})}function dL(n,e,t,s,r=.001){return z(()=>{const o=Nc(n,s),a=o.mean,i=o.variance,l=[];for(const f of Hn(0,n.rank))s.indexOf(f)!==-1?l.push(1):l.push(n.shape[f]);const u=F(a,l),c=F(i,l),h=e==null?null:F(e,l),d=t==null?null:F(t,l);return[ka(n,u,c,d,h,r),a,i]})}function pL(n,e,t,s,r=.001){return Ce(s.slice().sort(),Hn(0,n.rank-1))?hL(n,e,t,s,r):dL(n,e,t,s,r)}class bg extends Ie{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=je(e.betaInitializer||"zeros"),this.gammaInitializer=je(e.gammaInitializer||"ones"),this.movingMeanInitializer=je(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=je(e.movingVarianceInitializer||"ones"),this.betaConstraint=mt(e.betaConstraint),this.gammaConstraint=mt(e.gammaConstraint),this.betaRegularizer=qe(e.betaRegularizer),this.gammaRegularizer=qe(e.gammaRegularizer)}build(e){e=De(e);const t=this.axis>=0?this.axis:this.axis+e.length,s=e[t];if(s==null)throw new L(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new dt({ndim:e.length,axes:{[t]:s}})];const r=[s];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return z(()=>{const s=t.training==null?!1:t.training,r=ge(e),o=r.shape,a=o.length,i=Hn(0,a),l=this.axis>=0?this.axis:this.axis+a;i.splice(l,1);const u=Br(1,a);u[l]=o[l];const c=i.slice();c.sort();const h=!Ce(c,Hn(0,a).slice(0,a-1)),d=()=>{if(h){const b=F(this.movingMean.read(),u),w=F(this.movingVariance.read(),u),x=this.center?F(this.beta.read(),u):null,$=this.scale?F(this.gamma.read(),u):null;return ka(r,b,w,x,$,this.epsilon)}else return ka(r,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!s)return d();const[p,f,g]=pL(r,this.gamma.read(),this.beta.read(),i,this.epsilon),m=(b,w,x)=>{z(()=>{const $=1-x,C=b.read(),E=O(ae(C,w),$);b.write(ae(C,E))})};return(()=>{m(this.movingMean,f,this.momentum),m(this.movingVariance,g,this.momentum)})(),p})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ye(this.betaInitializer),gammaInitializer:Ye(this.gammaInitializer),movingMeanInitializer:Ye(this.movingMeanInitializer),movingVarianceInitializer:Ye(this.movingVarianceInitializer),betaRegularizer:Me(this.betaRegularizer),gammaRegularizer:Me(this.gammaRegularizer),betaConstraint:ft(this.betaConstraint),gammaConstraint:ft(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}bg.className="BatchNormalization";Z(bg);class xg extends Ie{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=je(e.betaInitializer||"zeros"),this.gammaInitializer=je(e.gammaInitializer||"ones"),this.betaRegularizer=qe(e.betaRegularizer),this.gammaRegularizer=qe(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=De(e);const t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let o=0;o=t)throw new Error(`Invalid axis: ${o}`);if(this.axis.length!==qs(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const s=this.axis.map(o=>e[o]),r=!0;this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,r):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,r):this.beta=null,this.built=!0}call(e,t){const s=ge(e),r=s.shape,o=r.length;return z(()=>{let{mean:i,variance:l}=Nc(s,this.axis,!0);const u=Br(1,o);for(const g of this.axis)u[g]=r[g];const c=g=>g!=null&&g.shape.length!==o?F(g,u):g;let h=this.scale?c(this.gamma.read()):null,d=this.center?c(this.beta.read()):null;const p=[],f=[];for(let g=0;g{if(n.rank!==4)throw new L(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);if(e==null&&(e=[[1,1],[1,1]]),e.length!==2||e[0].length!==2||e[1].length!==2)throw new L("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(t==null&&(t=jn()),t!=="channelsLast"&&t!=="channelsFirst")throw new L(`Unknown data format: ${t}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return t==="channelsFirst"?s=[[0,0],[0,0],e[0],e[1]]:s=[[0,0],e[0],e[1],[0,0]],dr(n,s)})}class wg extends Ie{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?jn():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new L(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,s;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],s=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new L(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new L(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);s=e.padding[1]}this.padding=[t,s]}this.inputSpec=[new dt({ndim:4})]}computeOutputShape(e){e=De(e);let t,s;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?s=e[3]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],e[1],t,s]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?s=e[2]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],t,s,e[3]])}call(e,t){return z(()=>fL(ge(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}wg.className="ZeroPadding2D";Z(wg);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function hh(n,e,t,s,r,o){return z(()=>{rt(r),r1(o),Sn(s),t==null&&(t=[1,1]),s==null&&(s="valid"),r==null&&(r=jn()),o==null&&(o="max"),n=Wm(n,r);let a;const i=s==="same"?"same":"valid";return o==="max"?a=Ic(n,e,t,i):a=mc(n,e,t,i),r==="channelsFirst"&&(a=ke(a,[0,3,1,2])),a})}function q1(n,e,t,s,r,o){return z(()=>{rt(r),r1(o),Sn(s),t==null&&(t=[1,1,1]),s==null&&(s="valid"),r==null&&(r=jn()),o==null&&(o="max"),n=W1(n,r);let a;const i=s==="same"?"same":"valid";return o==="max"?a=Rw(n,e,t,i):a=rw(n,e,t,i),r==="channelsFirst"&&(a=ke(a,[0,4,1,2,3])),a})}class K1 extends Ie{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new L(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(xt(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new L(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);xt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Sn(this.padding),this.inputSpec=[new dt({ndim:3})]}computeOutputShape(e){e=De(e);const t=Un(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return z(()=>{this.invokeCallHook(e,t),e=Vi(ge(e),2);const s=this.poolingFunction(ge(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Jr(s,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class vg extends K1{constructor(e){super(e)}poolingFunction(e,t,s,r,o){return rt(o),Sn(r),hh(e,t,s,r,o,"max")}}vg.className="MaxPooling1D";Z(vg);class $g extends K1{constructor(e){super(e)}poolingFunction(e,t,s,r,o){return rt(o),Sn(r),hh(e,t,s,r,o,"avg")}}$g.className="AveragePooling1D";Z($g);class X1 extends Ie{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new L(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];xt(this.poolSize,"poolSize"),xt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,rt(this.dataFormat),Sn(this.padding),this.inputSpec=[new dt({ndim:4})]}computeOutputShape(e){e=De(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Un(t,this.poolSize[0],this.padding,this.strides[0]),s=Un(s,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s]:[e[0],t,s,e[3]]}call(e,t){return z(()=>(this.invokeCallHook(e,t),this.poolingFunction(ge(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Sg extends X1{constructor(e){super(e)}poolingFunction(e,t,s,r,o){return rt(o),Sn(r),hh(e,t,s,r,o,"max")}}Sg.className="MaxPooling2D";Z(Sg);class Ig extends X1{constructor(e){super(e)}poolingFunction(e,t,s,r,o){return rt(o),Sn(r),hh(e,t,s,r,o,"avg")}}Ig.className="AveragePooling2D";Z(Ig);class Y1 extends Ie{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new L(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];xt(this.poolSize,"poolSize"),xt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,rt(this.dataFormat),Sn(this.padding),this.inputSpec=[new dt({ndim:5})]}computeOutputShape(e){e=De(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Un(t,this.poolSize[0],this.padding,this.strides[0]),s=Un(s,this.poolSize[1],this.padding,this.strides[1]),r=Un(r,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s,r]:[e[0],t,s,r,e[4]]}call(e,t){return z(()=>(this.invokeCallHook(e,t),this.poolingFunction(ge(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Ng extends Y1{constructor(e){super(e)}poolingFunction(e,t,s,r,o){return rt(o),Sn(r),q1(e,t,s,r,o,"max")}}Ng.className="MaxPooling3D";Z(Ng);class Cg extends Y1{constructor(e){super(e)}poolingFunction(e,t,s,r,o){return rt(o),Sn(r),q1(e,t,s,r,o,"avg")}}Cg.className="AveragePooling3D";Z(Cg);class Z1 extends Ie{constructor(e){super(e),this.inputSpec=[new dt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new xe}}class kg extends Z1{constructor(e){super(e||{})}call(e,t){return z(()=>{const s=ge(e);return et(s,1)})}}kg.className="GlobalAveragePooling1D";Z(kg);class Tg extends Z1{constructor(e){super(e||{})}call(e,t){return z(()=>{const s=ge(e);return En(s,1)})}}Tg.className="GlobalMaxPooling1D";Z(Tg);class J1 extends Ie{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,rt(this.dataFormat),this.inputSpec=[new dt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new xe}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Eg extends J1{call(e,t){return z(()=>{const s=ge(e);return this.dataFormat==="channelsLast"?et(s,[1,2]):et(s,[2,3])})}}Eg.className="GlobalAveragePooling2D";Z(Eg);class Ag extends J1{call(e,t){return z(()=>{const s=ge(e);return this.dataFormat==="channelsLast"?En(s,[1,2]):En(s,[2,3])})}}Ag.className="GlobalMaxPooling2D";Z(Ag);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Q1 extends Ie{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,s={}){const r=t.layer,o=Wn(r,s);delete t.layer;const a={layer:o};return Object.assign(a,t),new e(a)}}class Rg extends Q1{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=De(e),e.length<3)throw new L(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=De(e);const t=[e[0]].concat(e.slice(2)),s=this.layer.computeOutputShape(t),r=e[1];return[s[0],r].concat(s.slice(1))}call(e,t){return z(()=>(e=ge(e),H1((a,i)=>[ge(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}}Rg.className="TimeDistributed";Z(Rg);function mL(n){eo(f_,"BidirectionalMergeMode",n)}const gL="concat";class Dg extends Q1{constructor(e){super(e);const t=e.layer.getConfig(),s={};s.className=e.layer.getClassName(),s.config=t,this.forwardLayer=Wn(s),t.goBackwards=t.goBackwards!==!0;const r={};if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=Wn(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?gL:e.mergeMode,mL(this.mergeMode),e.weights)throw new xe("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,s=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,s)),this.backwardLayer.setWeights(e.slice(s))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let s,r,o;return this.returnState&&(o=t.slice(1)),s=t[0],s=s,this.mergeMode==="concat"?(s[s.length-1]*=2,r=[s]):this.mergeMode==null?r=[s,s.slice()]:r=[s],this.returnState?this.mergeMode==null?r.concat(o).concat(o.slice()):[s].concat(o).concat(o.slice()):jt(r)}apply(e,t){let s=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});const o=G1(e,s,r,this.numConstants);if(e=o.inputs,s=o.initialState,r=o.constants,Array.isArray(e)&&(s=e.slice(1),e=e[0]),(s==null||s.length===0)&&r==null)return super.apply(e,t);const a=[],i=[];if(s!=null){const u=s.length;if(u%2>0)throw new L("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=s,a.push(...s);const c=s.map(h=>new dt({shape:h.shape}));this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),i.push(...c)}if(r!=null)throw new xe("Support for constants in Bidirectional layers is not implemented yet.");const l=a[0]instanceof us;for(const u of a)if(u instanceof us!==l)throw new L("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(l){const u=[e].concat(a),c=this.inputSpec.concat(i),h=this.inputSpec;this.inputSpec=c;const d=super.apply(u,t);return this.inputSpec=h,d}else return super.apply(e,t)}call(e,t){return z(()=>{const s=t.initialState;let r,o;if(s==null)r=this.forwardLayer.call(e,t),o=this.backwardLayer.call(e,t);else{const l=s.slice(0,s.length/2),u=s.slice(s.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:l})),o=this.backwardLayer.call(e,Object.assign(t,{initialState:u}))}let a;this.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(o.slice(1))),r=r[0],o=o[0]),this.returnSequences&&(o=An(o,1));let i;return this.mergeMode==="concat"?i=mm([r,o]):this.mergeMode==="sum"?i=Y(r,o):this.mergeMode==="ave"?i=O(.5,Y(r,o)):this.mergeMode==="mul"?i=O(r,o):this.mergeMode==null&&(i=[r,o]),this.returnState?this.mergeMode==null?i.concat(a):[i].concat(a):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Er(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Er(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let s;if(this.returnSequences?this.mergeMode==null?s=[t,t]:s=t:this.mergeMode==null?s=[null,null]:s=null,this.returnState){const o=this.forwardLayer.states.map(a=>null);return Array.isArray(s)?s.concat(o).concat(o):[s].concat(o).concat(o)}else return s}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const s=Wn(t.layer);if(delete t.layer,t.numConstants!=null)throw new xe("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const r=t;return r.layer=s,new e(r)}}Dg.className="Bidirectional";Z(Dg);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Og extends Ie{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return z(()=>(e=ge(e),e.dtype!=="float32"&&(e=os(e,"float32")),Y(O(e,this.scale),this.offset)))}}Og.className="Rescaling";Z(Og);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const{resizeBilinear:yL,cropAndResize:bL}=Bn;class _g extends Ie{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,s,r,o,a,i,l){return z(()=>{let u,c=!1;const h=t/a,d=s/i,p=(r+t)/a,f=(o+s)/i,g=[h,d,p,f],m=[];e.rank===3?(c=!0,u=Xt([e])):u=e;for(let $=0;${const o=yL(e,[t,s]);return os(o,r)})}call(e,t){return z(()=>{const s=ge(e),r=s.dtype,o=s.shape,a=o[o.length-3],i=o[o.length-2];let l=0;a!==this.height&&(l=Math.floor((a-this.height)/2));let u=0;return i!==this.width&&(u=Math.floor((i-this.width)/2),u===0&&(u=1)),l>=0&&u>=0?this.centerCrop(s,l,u,this.height,this.width,a,i,r):this.upsize(e,this.height,this.width,r)})}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=De(e);const t=e.length-3,s=e.length-2;return e[t]=this.height,e[s]=this.width,e}}_g.className="CenterCrop";Z(_g);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function xL(n,e,t,s){let r=ge(n);if(r.dtype!=="int32"&&(r=os(r,"int32")),e==="int")return r;const o=r.shape;if(r.rank===0&&(r=Lt(r,-1)),e==="oneHot"&&r.shape[r.shape.length-1]!==1&&(r=Lt(r,-1)),r.rank>2)throw new L(`When outputMode is not int, maximum output rank is 2 Received outputMode ${e} and input shape ${o} which would result in output rank ${r.rank}.`);const a=["multiHot","oneHot"].includes(e),i=r;let l;if(typeof s<"u"&&e==="count"?l=nd(i,s,t,a):l=nd(i,[],t,a),e!=="tfIdf")return l;if(s)return O(l,s);throw new L("When outputMode is 'tfIdf', weights must be provided.")}/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Fg extends Ie{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return e=De(e),e==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return z(()=>{e=ge(e),e.dtype!=="int32"&&(e=os(e,"int32"));let s;if(typeof t.countWeights<"u"){if(this.outputMode!=="count")throw new L(`countWeights is not used when outputMode !== count. + Received countWeights=${t.countWeights}`);s=ge(t.countWeights)}const r=En(e),o=xa(e),a=Jt(this.numTokens,r).bufferSync().get(0),i=hr(o,0).bufferSync().get(0);if(!(a&&i))throw new L(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return xL(e,this.outputMode,this.numTokens,s)})}}Fg.className="CategoryEncoding";Z(Fg);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const wL=["bilinear","nearest"],yb=new Set(wL);class Lg extends Ie{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation)if(yb.has(e.interpolation))this.interpolation=e.interpolation;else throw new L(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){e=De(e);const t=e[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return z(()=>{const s=[this.height,this.width];if(this.interpolation==="bilinear")return Bn.resizeBilinear(e,s,!this.cropToAspectRatio);if(this.interpolation==="nearest")return Bn.resizeNearestNeighbor(e,s,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...yb]} are supported`)})}}Lg.className="Resizing";Z(Lg);/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class ev{constructor(e){this.seed=e}next(){if(this.seed!==void 0)return this.seed++}}ev.className="RandomSeed";/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class tv extends Ie{constructor(e){super(e),this.randomGenerator=new ev(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}tv.className="BaseRandomLayer";/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const vL=["bilinear","nearest"],bb=new Set(vL);class Pg extends tv{constructor(e){super(e);const{factor:t,interpolation:s="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new L(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new L(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper{const s=ge(e);this.imgHeight=s.shape[s.shape.length-3];const r=s.shape[s.shape.length-2];this.widthFactor=Zr([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let o=this.widthFactor.dataSync()[0]*r;o=Math.round(o);const a=[this.imgHeight,o];switch(this.interpolation){case"bilinear":return Bn.resizeBilinear(e,a);case"nearest":return Bn.resizeNearestNeighbor(e,a);default:throw new Error(`Interpolation is ${this.interpolation} + but only ${[...bb]} are supported`)}})}}Pg.className="RandomWidth";Z(Pg);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function $L(n){return new Po(n)}function SL(n){return new Mm(n)}function IL(n){return new Lm(n)}function NL(n){return new Pm(n)}function CL(n){return new zm(n)}function kL(n){return new Vm(n)}function TL(n){return new Bm(n)}function EL(n){return new ji(n)}function AL(n){return new Bo(n)}function RL(n){return new Um(n)}function DL(n){return new Vo(n)}function OL(n){return new Gm(n)}function _L(n){return new Hm(n)}function FL(n){return new jm(n)}function LL(n){return new qm(n)}function PL(n){return new Km(n)}function zL(n){return new ng(n)}function ML(n){return new eg(n)}function BL(n){return new ch(n)}function VL(n){return new Qm(n)}function WL(n){return new tg(n)}function UL(n){return new sg(n)}function GL(n){return new rg(n)}function HL(n){return new og(n)}function jL(n){return new ig(n)}function qL(n){return new lg(n)}function KL(n){return new cg(n)}function XL(n){return new pg(n)}function YL(n){return new hg(n)}function ZL(n){return new dg(n)}function JL(n){return new ug(n)}function QL(n){return new fg(n)}function eP(n){return new bg(n)}function tP(n){return new xg(n)}function nP(n){return new wg(n)}function zg(n){return new $g(n)}function sP(n){return zg(n)}function rP(n){return zg(n)}function Mg(n){return new Ig(n)}function oP(n){return Mg(n)}function aP(n){return Mg(n)}function Bg(n){return new Cg(n)}function iP(n){return Bg(n)}function lP(n){return Bg(n)}function uP(n){return new kg(n)}function cP(n){return new Eg(n)}function nv(n){return new Tg(n)}function sv(n){return new Ag(n)}function rv(n){return new vg(n)}function ov(n){return new Sg(n)}function hP(n){return new Ng(n)}function dP(n){return new Ym(n)}function pP(n){return new ih(n)}function fP(n){return new Zm(n)}function mP(n){return new Ki(n)}function gP(n){return new Xm(n)}function yP(n){return new ah(n)}function bP(n){return new Jm(n)}function xP(n){return new uh(n)}function wP(n){return new ds(n)}function vP(n){return new lh(n)}function $P(n){return new Dg(n)}function SP(n){return new Rg(n)}const IP=nv,NP=sv,CP=rv,kP=ov;function TP(n){return new mg(n)}function EP(n){return new gg(n)}function AP(n){return new yg(n)}function RP(n){return new ag(n)}function DP(n){return new Og(n)}function OP(n){return new _g(n)}function _P(n){return new Lg(n)}function FP(n){return new Fg(n)}function LP(n){return new Pg(n)}const KJ=Object.freeze(Object.defineProperty({__proto__:null,Layer:Ie,RNN:ds,RNNCell:qi,activation:zL,add:qL,alphaDropout:AP,average:KL,averagePooling1d:zg,averagePooling2d:Mg,averagePooling3d:Bg,avgPool1d:sP,avgPool2d:oP,avgPool3d:iP,avgPooling1d:rP,avgPooling2d:aP,avgPooling3d:lP,batchNormalization:eP,bidirectional:$P,categoryEncoding:FP,centerCrop:OP,concatenate:XL,conv1d:EL,conv2d:AL,conv2dTranspose:RL,conv3d:DL,conv3dTranspose:OL,convLstm2d:bP,convLstm2dCell:xP,cropping2D:FL,dense:ML,depthwiseConv2d:PL,dot:QL,dropout:BL,elu:SL,embedding:jL,flatten:WL,gaussianDropout:EP,gaussianNoise:TP,globalAveragePooling1d:uP,globalAveragePooling2d:cP,globalMaxPool1d:IP,globalMaxPool2d:NP,globalMaxPooling1d:nv,globalMaxPooling2d:sv,gru:dP,gruCell:pP,input:sL,inputLayer:$L,layerNormalization:tP,leakyReLU:NL,lstm:fP,lstmCell:mP,masking:RP,maxPool1d:CP,maxPool2d:kP,maxPooling1d:rv,maxPooling2d:ov,maxPooling3d:hP,maximum:YL,minimum:ZL,multiply:JL,permute:HL,prelu:CL,randomWidth:LP,reLU:IL,repeatVector:UL,rescaling:DP,reshape:GL,resizing:_P,rnn:wP,separableConv2d:_L,simpleRNN:gP,simpleRNNCell:yP,softmax:kL,spatialDropout1d:VL,stackedRNNCells:vP,thresholdedReLU:TL,timeDistributed:SP,upSampling2d:LL,zeroPadding2d:nP},Symbol.toStringTag,{value:"Module"}));function PP(n,e){return Am(n,e)}function zP(n,e){return y1(n,e)}function MP(n,e){return b1(n,e)}function BP(n,e){return Rm(n,e)}function VP(n,e){return Dm(n,e)}function WP(n,e){return g1(n,e)}function UP(n,e){return IF(n,e)}function GP(n,e){return Em(n,e)}function HP(n,e){return sh(n,e)}function jP(n,e){return zo(n,e)}function qP(n,e){return zo(n,e)}function KP(n,e){return zo(n,e)}function XP(n,e){return to(n,e)}function YP(n,e){return to(n,e)}function ZP(n,e){return to(n,e)}function JP(n,e){return NF(n,e)}const XJ=Object.freeze(Object.defineProperty({__proto__:null,MAPE:qP,MSE:YP,binaryAccuracy:PP,binaryCrossentropy:zP,categoricalAccuracy:BP,categoricalCrossentropy:VP,cosineProximity:GP,mape:KP,meanAbsoluteError:HP,meanAbsolutePercentageError:jP,meanSquaredError:XP,mse:ZP,precision:WP,r2Score:JP,recall:UP,sparseCategoricalAccuracy:MP},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const YJ=Object.freeze(Object.defineProperty({__proto__:null,modelFromJSON:eL},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function QP(n){return new Hi(n)}function e3(n){return rL(n)}function t3(n){return oL(n)}const ZJ=Object.freeze(Object.defineProperty({__proto__:null,l1:e3,l1l2:QP,l2:t3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class n3 extends No{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Xs))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function il(n,e){return ne}class s3 extends n3{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new xe("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=il:this.mode==="max"?this.monitorFunc=xb:this.monitor.indexOf("acc")!==-1?this.monitorFunc=xb:this.monitorFunc=il,this.monitorFunc===il&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===il?1/0:-1/0}async onEpochEnd(e,t){await Bs(t);const s=this.getMonitorValue(t);s!=null&&(this.monitorFunc(s-this.minDelta,this.best)?(this.best=s,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});const t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}function r3(n){return new s3(n)}const JJ={earlyStopping:r3};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const o3=B();o3.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,n=>{n&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */var en;(function(n){n[n.DT_INVALID=0]="DT_INVALID",n[n.DT_FLOAT=1]="DT_FLOAT",n[n.DT_DOUBLE=2]="DT_DOUBLE",n[n.DT_INT32=3]="DT_INT32",n[n.DT_UINT8=4]="DT_UINT8",n[n.DT_INT16=5]="DT_INT16",n[n.DT_INT8=6]="DT_INT8",n[n.DT_STRING=7]="DT_STRING",n[n.DT_COMPLEX64=8]="DT_COMPLEX64",n[n.DT_INT64=9]="DT_INT64",n[n.DT_BOOL=10]="DT_BOOL",n[n.DT_QINT8=11]="DT_QINT8",n[n.DT_QUINT8=12]="DT_QUINT8",n[n.DT_QINT32=13]="DT_QINT32",n[n.DT_BFLOAT16=14]="DT_BFLOAT16",n[n.DT_QINT16=15]="DT_QINT16",n[n.DT_QUINT16=16]="DT_QUINT16",n[n.DT_UINT16=17]="DT_UINT16",n[n.DT_COMPLEX128=18]="DT_COMPLEX128",n[n.DT_HALF=19]="DT_HALF",n[n.DT_RESOURCE=20]="DT_RESOURCE",n[n.DT_VARIANT=21]="DT_VARIANT",n[n.DT_UINT32=22]="DT_UINT32",n[n.DT_UINT64=23]="DT_UINT64",n[n.DT_FLOAT_REF=101]="DT_FLOAT_REF",n[n.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",n[n.DT_INT32_REF=103]="DT_INT32_REF",n[n.DT_UINT8_REF=104]="DT_UINT8_REF",n[n.DT_INT16_REF=105]="DT_INT16_REF",n[n.DT_INT8_REF=106]="DT_INT8_REF",n[n.DT_STRING_REF=107]="DT_STRING_REF",n[n.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",n[n.DT_INT64_REF=109]="DT_INT64_REF",n[n.DT_BOOL_REF=110]="DT_BOOL_REF",n[n.DT_QINT8_REF=111]="DT_QINT8_REF",n[n.DT_QUINT8_REF=112]="DT_QUINT8_REF",n[n.DT_QINT32_REF=113]="DT_QINT32_REF",n[n.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",n[n.DT_QINT16_REF=115]="DT_QINT16_REF",n[n.DT_QUINT16_REF=116]="DT_QUINT16_REF",n[n.DT_UINT16_REF=117]="DT_UINT16_REF",n[n.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",n[n.DT_HALF_REF=119]="DT_HALF_REF",n[n.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",n[n.DT_VARIANT_REF=121]="DT_VARIANT_REF",n[n.DT_UINT32_REF=122]="DT_UINT32_REF",n[n.DT_UINT64_REF=123]="DT_UINT64_REF"})(en||(en={}));var wb;(function(n){(function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"})(n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))})(wb||(wb={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vg={};function QJ(n,e){const t={tfOpName:n,category:"custom",inputs:[],attrs:[],customExecutor:e};Vg[n]=t}function av(n){return Vg[n]}function e9(n){delete Vg[n]}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v(n,e,t,s,r){const o=e.inputParams[n];if(o&&o.inputIndexStart!==void 0){const i=o.inputIndexStart,l=o.inputIndexEnd===0?void 0:o.inputIndexEnd===void 0?i+1:o.inputIndexEnd,u=i<0?e.inputNames.length+i:i;if(o.type==="tensor")return Ct(e.inputNames[u],t,s,r);if(o.type==="tensors"){const d=e.inputs.slice(i,l);return e.inputNames.slice(i,l).filter((f,g)=>{var m;return((m=d[g])===null||m===void 0?void 0:m.op)!=="NoOp"}).map(f=>Ct(f,t,s,r))}const c=Ct(e.inputNames[u],t,s,r),h=c.dataSync();return o.type==="number"?h[0]:bn(c.shape,h)}const a=e.attrParams[n];return a&&a.value}function Ct(n,e,t,s){const[r,o]=nn(n,t);if(s!=null){const i=s.getHashTableHandleByName(r);if(i!=null)return i}const a=t.currentContextIds.find(i=>!!e[Jl(r,i)]);return a!==void 0?e[Jl(r,a)][o]:void 0}function vb(n,e,t){return e[Jl(n,t.currentContextId)]}function ys(n,e){const[t,s,r]=nn(n,e);return[Jl(t,e&&e.currentContextId),s,r]}function Jl(n,e){return e?`${n}-${e}`:n}function nn(n,e){if(n==="")return["",0,void 0];const t=e!=null&&e.parseNodeNameCache!=null;if(t){const o=e.parseNodeNameCache.get(n);if(o!=null)return o}const s=n.split(":");let r;if(s.length===1)r=[n,0,void 0];else{const o=s[0],a=s.length===3?s[1]:void 0,i=Number(s[s.length-1]);r=[o,i,a]}return t&&e.parseNodeNameCache.set(n,r),r}function Nl(n,e,t){let s=v("pad",n,e,t);if(s==="explicit"){s=v("explicitPaddings",n,e,t);const r=[[0,0],[0,0],[0,0],[0,0]];for(let o=0;o<4;o++)r[o][0]=s[o*2],r[o][1]=s[o*2+1];return r}return s}function bs(n){return n.kept?n:vs(n)}/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a3=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],i3=Object.freeze(Object.defineProperty({__proto__:null,json:a3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const l3=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],u3=Object.freeze(Object.defineProperty({__proto__:null,json:l3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const c3=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],h3=Object.freeze(Object.defineProperty({__proto__:null,json:c3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const d3=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],p3=Object.freeze(Object.defineProperty({__proto__:null,json:d3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const f3=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],m3=Object.freeze(Object.defineProperty({__proto__:null,json:f3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const g3=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],y3=Object.freeze(Object.defineProperty({__proto__:null,json:g3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const b3=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],x3=Object.freeze(Object.defineProperty({__proto__:null,json:b3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const w3=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],v3=Object.freeze(Object.defineProperty({__proto__:null,json:w3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $3=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],S3=Object.freeze(Object.defineProperty({__proto__:null,json:$3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const I3=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],N3=Object.freeze(Object.defineProperty({__proto__:null,json:I3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const C3=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}],k3=Object.freeze(Object.defineProperty({__proto__:null,json:C3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const T3=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}],E3=Object.freeze(Object.defineProperty({__proto__:null,json:T3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const A3=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}],R3=Object.freeze(Object.defineProperty({__proto__:null,json:A3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const D3=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],O3=Object.freeze(Object.defineProperty({__proto__:null,json:D3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _3=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],F3=Object.freeze(Object.defineProperty({__proto__:null,json:_3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const L3=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],P3=Object.freeze(Object.defineProperty({__proto__:null,json:L3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const z3=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],M3=Object.freeze(Object.defineProperty({__proto__:null,json:z3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const B3=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],V3=Object.freeze(Object.defineProperty({__proto__:null,json:B3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2023 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const W3=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],U3=Object.freeze(Object.defineProperty({__proto__:null,json:W3},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $b{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[i3,u3,h3,p3,m3,y3,x3,v3,S3,N3,k3,E3,R3,O3,F3,P3,M3,V3,U3],t=[].concat(...e.map(s=>s.json));this.opMappers=t.reduce((s,r)=>(s[r.tfOpName]=r,s),{})}transformGraph(e,t={}){const s=e.node,r=[],o=[],a=[],i=s.reduce((g,m)=>(g[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?r.push(g[m.name]):m.op==="Const"?o.push(g[m.name]):(m.input==null||m.input.length===0)&&a.push(g[m.name]),g),{});let l=[];const u=[];let c={},h={};t!=null&&(c=this.mapSignatureEntries(t.inputs),h=this.mapSignatureEntries(t.outputs));const d=Object.keys(i);d.forEach(g=>{const m=i[g];m.inputNames.forEach((y,b)=>{const[w,,x]=ys(y),$=i[w];if($.outputs!=null){const C=$.outputs.indexOf(x);if(C!==-1){const E=`${w}:${C}`;m.inputNames[b]=E}}m.inputs.push($),$.children.push(m)})}),Object.keys(h).length===0?d.forEach(g=>{const m=i[g];m.children.length===0&&u.push(m)}):Object.keys(h).forEach(g=>{const[m]=ys(g),y=i[m];y!=null&&(y.signatureKey=h[g],u.push(y))}),Object.keys(c).length>0?Object.keys(c).forEach(g=>{const[m]=ys(g),y=i[m];y&&(y.signatureKey=c[g],l.push(y))}):l=r;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((g,m)=>(g[m.signature.name]=this.mapFunction(m),g),{}));const f={nodes:i,inputs:l,outputs:u,weights:o,placeholders:r,signature:t,functions:p};return a.length>0&&(f.initNodes=a),f}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,s)=>(t[e[s].name]=s,t),{})}mapNode(e){const t=av(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});const s={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(r=>r.startsWith("^")?r.slice(1):r),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(s.inputParams=t.inputs.reduce((r,o)=>(r[o.name]={type:o.type,inputIndexStart:o.start,inputIndexEnd:o.end},r),{})),t.attrs!=null&&(s.attrParams=t.attrs.reduce((r,o)=>{const a=o.type;let i;switch(o.type){case"string":i=bd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=bd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"string[]":i=Nd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=Nd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"number":i=wd(e.attr,o.tfName,o.defaultValue||0),i===void 0&&o.tfDeprecatedName&&(i=wd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"number[]":i=Id(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=Id(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"bool":i=xd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=xd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"bool[]":i=kd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=kd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"shape":i=Sd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=Sd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"shape[]":i=Cd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=Cd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"dtype":i=vd(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=vd(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"dtype[]":i=$d(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=$d(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"func":i=Sb(e.attr,o.tfName,o.defaultValue),i===void 0&&o.tfDeprecatedName&&(i=Sb(e.attr,o.tfDeprecatedName,o.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${o.type} for op: ${e.op}`)}return r[o.name]={value:i,type:a},r},{})),s}mapFunction(e){const t=e.nodeDef,s=[],r=[];let o={};t!=null&&(o=t.reduce((h,d)=>(h[d.name]=this.mapNode(d),d.op==="Const"&&r.push(h[d.name]),h),{}));const a=[],i=[];e.signature.inputArg.forEach(h=>{const[d]=ys(h.name),p={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Wg(h.type),type:"dtype"}},children:[]};p.signatureKey=h.name,a.push(p),o[d]=p}),Object.keys(o).forEach(h=>{const d=o[h];d.inputNames.forEach((p,f)=>{const[g,,m]=ys(p),y=o[g];if(y.outputs!=null){const b=y.outputs.indexOf(m);if(b!==-1){const w=`${g}:${b}`;d.inputNames[f]=w}}d.inputs.push(y),y.children.push(d)})});const u=e.ret;e.signature.outputArg.forEach(h=>{const[d,p]=ys(u[h.name]),f=o[d];f!=null&&(f.defaultOutput=p,i.push(f))});const c=this.mapArgsToSignature(e);return{nodes:o,inputs:a,outputs:i,weights:r,placeholders:s,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,s)=>(t[s.name]=this.mapArgToTensorInfo(s),t),{}),outputs:e.signature.outputArg.reduce((t,s)=>(t[s.name]=this.mapArgToTensorInfo(s,e.ret),t),{})}}mapArgToTensorInfo(e,t){let s=e.name;return t!=null&&(s=t[s]),{name:s,dtype:e.type}}}function G3(n){const e=B().global;if(typeof e.atob<"u")return e.atob(n);if(typeof Buffer<"u")return new Buffer(n,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function iv(n,e){const t=Array.isArray(n)?String.fromCharCode.apply(null,n):G3(n);return e?t:t.toLowerCase()}function bd(n,e,t,s=!1){const r=n[e];return r!=null?iv(r.s,s):t}function xd(n,e,t){const s=n[e];return s?s.b:t}function wd(n,e,t){const s=n[e]||{},r=s.i!=null?s.i:s.f!=null?s.f:t;return typeof r=="number"?r:parseInt(r,10)}function Wg(n){switch(typeof n=="string"&&(n=en[n]),n){case en.DT_FLOAT:case en.DT_HALF:return"float32";case en.DT_INT32:case en.DT_INT64:case en.DT_INT8:case en.DT_UINT8:return"int32";case en.DT_BOOL:return"bool";case en.DT_DOUBLE:return"float32";case en.DT_STRING:return"string";case en.DT_COMPLEX64:case en.DT_COMPLEX128:return"complex64";default:return null}}function Sb(n,e,t){const s=n[e];return s&&s.func?s.func.name:t}function vd(n,e,t){const s=n[e];return s&&s.type?Wg(s.type):t}function $d(n,e,t){const s=n[e];return s&&s.list&&s.list.type?s.list.type.map(r=>Wg(r)):t}function lv(n){if(!n.unknownRank)return n.dim!=null?n.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function Sd(n,e,t){const s=n[e];return s&&s.shape?lv(s.shape):t}function Id(n,e,t){const s=n[e];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):t}function Nd(n,e,t,s=!1){const r=n[e];return r&&r.list&&r.list.s?r.list.s.map(o=>iv(o,s)):t}function Cd(n,e,t){const s=n[e];return s&&s.list&&s.list.shape?s.list.shape.map(r=>lv(r)):t}function kd(n,e,t){const s=n[e];return s&&s.list&&s.list.b?s.list.b:t}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class H3{constructor(e,t,s){this.node=e,this.tensorMap=t,this.context=s,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(r=>this.getInput(r)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((r,o)=>(r[o]=this.getAttr(o),r),{}))}getInput(e){return Ct(e,this.tensorMap,this.context)}getAttr(e,t){const s=this.node.rawAttrs[e];if(s.tensor!=null)return Ct(e,this.tensorMap,this.context);if(s.i!=null||s.f!=null)return wd(this.node.rawAttrs,e,t);if(s.s!=null)return bd(this.node.rawAttrs,e,t);if(s.b!=null)return xd(this.node.rawAttrs,e,t);if(s.shape!=null)return Sd(this.node.rawAttrs,e,t);if(s.type!=null)return vd(this.node.rawAttrs,e,t);if(s.list!=null){if(s.list.i!=null||s.list.f!=null)return Id(this.node.rawAttrs,e,t);if(s.list.s!=null)return Nd(this.node.rawAttrs,e,t);if(s.list.shape!=null)return Cd(this.node.rawAttrs,e,t);if(s.list.b!=null)return kd(this.node.rawAttrs,e,t);if(s.list.type!=null)return $d(this.node.rawAttrs,e,t)}return t}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _t=Object.freeze(Object.defineProperty({__proto__:null,OP_SCOPE_SUFFIX:Ox,abs:lt,acos:Yx,acosh:Zx,add:Y,addN:WN,all:of,any:Bl,argMax:vo,argMin:Jx,asin:Qx,asinh:ew,atan:tw,atan2:nw,atanh:sw,avgPool:mc,avgPool3d:rw,basicLSTMCell:hC,batchNorm:Ri,batchNorm2d:ow,batchNorm3d:aw,batchNorm4d:iw,batchToSpaceND:gc,bincount:lw,bitwiseAnd:wC,booleanMaskAsync:pE,broadcastArgs:$C,broadcastTo:yo,buffer:ve,cast:ee,ceil:uw,clipByValue:ln,clone:vs,complex:Js,concat:at,concat1d:cw,concat2d:hw,concat3d:dw,concat4d:pw,conv1d:lf,conv2d:tr,conv2dTranspose:cf,conv3d:fw,conv3dTranspose:gw,cos:yc,cosh:hf,cosineWindow:Lf,cumprod:Vl,cumsum:df,denseBincount:nd,depthToSpace:yw,depthwiseConv2d:Di,diag:HC,dilation2d:bw,div:ce,divNoNan:xw,dot:ww,dropout:qw,einsum:po,elu:Oi,enclosingPowerOfTwo:Kw,ensureShape:tk,equal:wn,erf:pf,euclideanNorm:Sw,exp:un,expandDims:Lt,expm1:Iw,eye:mf,fft:Rc,fill:Do,floor:Fi,floorDiv:rf,fused:FE,gather:Li,gatherND:SE,greater:Jt,greaterEqual:hr,ifft:Ia,imag:bc,image:Bn,inTopKAsync:kE,irfft:Rf,isFinite:Nw,isInf:Cw,isNaN:kw,leakyRelu:xc,less:wa,lessEqual:Yr,linalg:n0,linspace:kk,localResponseNormalization:Tw,log:vn,log1p:wc,logSigmoid:Ew,logSoftmax:gf,logSumExp:$c,logicalAnd:Gn,logicalNot:Sc,logicalOr:yf,logicalXor:Aw,losses:dR,lowerBound:Uk,matMul:Ne,max:En,maxPool:Ic,maxPool3d:Rw,maxPoolWithArgmax:qk,maximum:Os,mean:et,meshgrid:Yk,min:xa,minimum:zr,mirrorPad:Dw,mod:Ow,moments:Nc,movingAverage:gE,mul:O,multiRNNCell:nT,multinomial:rT,neg:Ge,norm:_i,notEqual:$o,oneHot:va,ones:rn,onesLike:$n,op:D,outerProduct:uT,pad:dr,pad1d:dT,pad2d:fT,pad3d:gT,pad4d:bT,pool:_w,pow:Ns,prelu:kc,print:Xx,prod:Fw,raggedGather:CT,raggedRange:TT,raggedTensorToTensor:AT,rand:DT,randomGamma:u2,randomNormal:$f,randomStandardNormal:d2,randomUniform:Zr,randomUniformInt:m2,range:So,real:$a,reciprocal:zw,relu:hs,relu6:Sf,reshape:F,reverse:An,reverse1d:$2,reverse2d:I2,reverse3d:C2,reverse4d:T2,rfft:Dc,round:If,rsqrt:Nf,scalar:pe,scatterND:bE,searchSorted:bf,selu:Cf,separableConv2d:kf,setdiff1dAsync:_2,sigmoid:ss,sign:Mw,signal:hR,sin:Tf,sinh:Ef,slice:Te,slice1d:Tc,slice2d:Af,slice3d:Ec,slice4d:Sa,softmax:Ac,softplus:Oo,spaceToBatchND:Cc,sparse:pR,sparseToDense:vE,spectral:cR,split:on,sqrt:At,square:ze,squaredDifference:Df,squeeze:Jr,stack:Xt,step:Fo,stridedSlice:Bw,string:fR,sub:ae,sum:ie,tan:Vw,tanh:Lr,tensor:xn,tensor1d:Pt,tensor2d:Tr,tensor3d:Ww,tensor4d:eE,tensor5d:tE,tensor6d:nE,tensorScatterUpdate:rE,tile:kn,topk:Uw,transpose:ke,truncatedNormal:_f,unique:Gw,unsortedSegmentSum:Ff,unstack:Rn,upperBound:cE,variable:Hw,where:Tt,whereAsync:jw,zeros:ct,zerosLike:Ee},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const j3=(n,e,t,s=_t)=>{switch(n.op){case"BiasAdd":case"AddV2":case"Add":return[s.add(v("a",n,e,t),v("b",n,e,t))];case"AddN":return[s.addN(v("tensors",n,e,t))];case"FloorMod":case"Mod":return[s.mod(v("a",n,e,t),v("b",n,e,t))];case"Mul":return[s.mul(v("a",n,e,t),v("b",n,e,t))];case"RealDiv":case"Div":return[s.div(v("a",n,e,t),v("b",n,e,t))];case"DivNoNan":return[s.divNoNan(v("a",n,e,t),v("b",n,e,t))];case"FloorDiv":return[s.floorDiv(v("a",n,e,t),v("b",n,e,t))];case"Sub":return[s.sub(v("a",n,e,t),v("b",n,e,t))];case"Minimum":return[s.minimum(v("a",n,e,t),v("b",n,e,t))];case"Maximum":return[s.maximum(v("a",n,e,t),v("b",n,e,t))];case"Pow":return[s.pow(v("a",n,e,t),v("b",n,e,t))];case"SquaredDifference":return[s.squaredDifference(v("a",n,e,t),v("b",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const q3=(n,e,t,s=_t)=>{switch(n.op){case"Abs":case"ComplexAbs":return[s.abs(v("x",n,e,t))];case"Acos":return[s.acos(v("x",n,e,t))];case"Acosh":return[s.acosh(v("x",n,e,t))];case"Asin":return[s.asin(v("x",n,e,t))];case"Asinh":return[s.asinh(v("x",n,e,t))];case"Atan":return[s.atan(v("x",n,e,t))];case"Atan2":return[s.atan2(v("x",n,e,t),v("y",n,e,t))];case"Atanh":return[s.atanh(v("x",n,e,t))];case"Ceil":return[s.ceil(v("x",n,e,t))];case"Complex":return[s.complex(v("real",n,e,t),v("imag",n,e,t))];case"Cos":return[s.cos(v("x",n,e,t))];case"Cosh":return[s.cosh(v("x",n,e,t))];case"Elu":return[s.elu(v("x",n,e,t))];case"Erf":return[s.erf(v("x",n,e,t))];case"Exp":return[s.exp(v("x",n,e,t))];case"Expm1":return[s.expm1(v("x",n,e,t))];case"Floor":return[s.floor(v("x",n,e,t))];case"Log":return[s.log(v("x",n,e,t))];case"Log1p":return[s.log1p(v("x",n,e,t))];case"Imag":return[s.imag(v("x",n,e,t))];case"Neg":return[s.neg(v("x",n,e,t))];case"Reciprocal":return[s.reciprocal(v("x",n,e,t))];case"Real":return[s.real(v("x",n,e,t))];case"Relu":return[s.relu(v("x",n,e,t))];case"Round":return[s.round(v("x",n,e,t))];case"Selu":return[s.selu(v("x",n,e,t))];case"Sigmoid":return[s.sigmoid(v("x",n,e,t))];case"Sin":return[s.sin(v("x",n,e,t))];case"Sign":return[s.sign(v("x",n,e,t))];case"Sinh":return[s.sinh(v("x",n,e,t))];case"Softplus":return[s.softplus(v("x",n,e,t))];case"Sqrt":return[s.sqrt(v("x",n,e,t))];case"Square":return[s.square(v("x",n,e,t))];case"Tanh":return[s.tanh(v("x",n,e,t))];case"Tan":return[s.tan(v("x",n,e,t))];case"ClipByValue":return[s.clipByValue(v("x",n,e,t),v("clipValueMin",n,e,t),v("clipValueMax",n,e,t))];case"Relu6":return[s.relu6(v("x",n,e,t))];case"Rsqrt":return[s.rsqrt(Ct(n.inputNames[0],e,t))];case"LeakyRelu":return[s.leakyRelu(v("x",n,e,t),v("alpha",n,e,t))];case"Prelu":return[s.prelu(v("x",n,e,t),v("alpha",n,e,t))];case"IsNan":return[s.isNaN(Ct(n.inputNames[0],e,t))];case"IsInf":return[s.isInf(Ct(n.inputNames[0],e,t))];case"IsFinite":return[s.isFinite(Ct(n.inputNames[0],e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cn(n,e,t=""){if(!(typeof n=="number"||typeof e=="number")){I(n.length===e.length,()=>t+` Shapes ${n} and ${e} must match`);for(let s=0;st+` Shapes ${n} and ${e} must match`)}}}function Ib(n){return!(typeof n=="number"||n.some(e=>e<0))}function na(n,e,t){let s=Td(n,t);const r=!Ib(s);if(r&&e.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&e.forEach(o=>{s=Td(o.shape,s)}),!Ib(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function Td(n,e){if(typeof n=="number")return e;if(typeof e=="number")return n;if(n.length!==e.length)throw new Error(`Incompatible ranks during merge: ${n} vs. ${e}`);const t=[];for(let s=0;s=0&&o>=0&&r!==o)throw new Error(`Incompatible shape during merge: ${n} vs. ${e}`);t[s]=r>=0?r:o}return t}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class K3{constructor(e,t,s,r,o,a,i){this.name=e,this.dtype=t,this.maxSize=s,this.elementShape=r,this.identicalElementShapes=o,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=pe(0),bt(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const s=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, + because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Cn(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),s.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(s.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);s.tensor=t,bt(t),s.written=!0,this.tensors[e]=s}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((s,r)=>this.write(s,t[r]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let r=0;r=this.maxSize)throw new Error(`Max index must be < array size (${s} vs. ${this.maxSize})`);this.writeMany(e,Rn(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let s=0;const r=e.map(l=>(s+=l,s));if(s!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to + tensor.shape[0], but sum of lengths is + ${s}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const o=s===0?0:t.size/s,a=[];z(()=>{t=F(t,[1,s,o]);for(let l=0;l{if(s!==o.dtype)throw new Error(`Invalid data types; op elements ${s}, but list elements ${o.dtype}`);Cn(t,o.shape,"TensorList shape mismatch: "),bt(o)}),this.idTensor=pe(0),this.maxNumElements=r,bt(this.idTensor)}copy(){return new Vr([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,s=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(s!==-1&&this.tensors.length!==s)throw new Error(`Operation expected a list with ${s} elements but got a list with ${this.tensors.length} elements.`);Cn(e,this.elementShape,"TensorList shape mismatch: ");const r=na(this.elementShape,this.tensors,e);return z(()=>{const o=this.tensors.map(a=>F(a,r));return Xt(o,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");const s=na(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Cn(r.shape,e,"TensorList shape mismatch: "),F(r,s)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Cn(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");bt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new Vr([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let s=0;sthis.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);Cn(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=na(this.elementShape,this.tensors,t);return F(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Cn(this.elementShape,t.shape,"TensorList shape mismatch: "),bt(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,s){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Cn(this.elementShape,s,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=na(this.elementShape,this.tensors,s);return e.length===0?xn([],[0].concat(r)):z(()=>{const o=e.map(a=>F(this.tensors[a],r));return Xt(o,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Cn(this.elementShape,t,"TensorList shape mismatch: ");const s=na(this.elementShape,this.tensors,t);return this.size()===0?xn([],[0].concat(s)):z(()=>{const r=this.tensors.map(o=>F(o,s));return at(r,0)})}}function X3(n,e,t){const s=n.dtype;if(n.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${n.shape}`);if(n.dtype!==t)throw new Error(`Invalid data types; op elements ${n.dtype}, but list elements ${t}`);const r=n.shape.slice(1);Cn(r,e,"TensorList shape mismatch: ");const o=Rn(n);return new Vr(o,e,s)}function Y3(n,e,t,s){return new Vr([],n,e,s)}function Z3(n,e,t,s){if(e.length!==n.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${n.shape[0]}`);const r=Math.max(...e);if(s!=null&&s!==-1&&r>=s)throw new Error(`Max index must be < array size (${r} vs. ${s})`);const o=new Vr([],t,n.dtype,s),a=Rn(n,0);return e.forEach((i,l)=>{o.setItem(i,a[l])}),o}function J3(n,e,t){let s=0;const r=e.map(c=>(s+=c,s));if(s!==n.shape[0])throw new Error(`Expected sum of lengths to be equal to + tensor.shape[0], but sum of lengths is + ${s}, and tensor's shape is: ${n.shape}`);const o=n.shape.slice(1),a=Td(o,t),i=s===0?0:n.size/s,l=z(()=>{const c=[];n=F(n,[1,s,i]);for(let h=0;h{switch(n.op){case"If":case"StatelessIf":{const s=v("thenBranch",n,e,t),r=v("elseBranch",n,e,t),o=v("cond",n,e,t),a=v("args",n,e,t);return(await o.data())[0]?t.functionMap[s].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap):t.functionMap[r].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{const s=v("body",n,e,t),r=v("cond",n,e,t),o=v("args",n,e,t),a=await t.functionMap[r].executeFunctionAsync(o,t.tensorArrayMap,t.tensorListMap),i=o.map(c=>c.id);let l=await a[0].data();a.forEach(c=>{!c.kept&&i.indexOf(c.id)===-1&&c.dispose()});let u=o;for(;l[0];){const c=u;u=await t.functionMap[s].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);const h=u.map(p=>p.id);c.forEach(p=>{!p.kept&&i.indexOf(p.id)===-1&&h.indexOf(p.id)===-1&&p.dispose()});const d=await t.functionMap[r].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);l=await d[0].data(),d.forEach(p=>{!p.kept&&i.indexOf(p.id)===-1&&h.indexOf(p.id)===-1&&p.dispose()})}return u}case"LoopCond":{const s=v("pred",n,e,t);return[bs(s)]}case"Switch":{const s=v("pred",n,e,t);let r=v("data",n,e,t);return r.kept||(r=bs(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{const s=n.inputNames.find(r=>Ct(r,e,t)!==void 0);if(s){const r=Ct(s,e,t);return[bs(r)]}return}case"Enter":{const s=v("frameName",n,e,t),r=v("tensor",n,e,t);return t.enterFrame(s),[bs(r)]}case"Exit":{const s=v("tensor",n,e,t);return t.exitFrame(),[bs(s)]}case"NextIteration":{const s=v("tensor",n,e,t);return t.nextIteration(),[bs(s)]}case"TensorArrayV3":{const s=v("size",n,e,t),r=v("dtype",n,e,t),o=v("elementShape",n,e,t),a=v("dynamicSize",n,e,t),i=v("clearAfterRead",n,e,t),l=v("identicalElementShapes",n,e,t),u=v("name",n,e,t),c=new K3(u,r,s,o,l,a,i);return t.addTensorArray(c),[c.idTensor,pe(1)]}case"TensorArrayWriteV3":{const s=v("tensorArrayId",n,e,t),r=v("index",n,e,t),o=v("tensor",n,e,t),a=t.getTensorArray(s.id);return a.write(r,o),[a.idTensor]}case"TensorArrayReadV3":{const s=v("tensorArrayId",n,e,t),r=v("index",n,e,t);return[t.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{const s=v("tensorArrayId",n,e,t),r=v("indices",n,e,t),o=v("dtype",n,e,t);return[t.getTensorArray(s.id).gather(r,o)]}case"TensorArrayScatterV3":{const s=v("tensorArrayId",n,e,t),r=v("indices",n,e,t),o=v("tensor",n,e,t),a=t.getTensorArray(s.id);return a.scatter(r,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=v("tensorArrayId",n,e,t),r=t.getTensorArray(s.id),o=v("dtype",n,e,t);return[r.concat(o)]}case"TensorArraySplitV3":{const s=v("tensorArrayId",n,e,t),r=v("tensor",n,e,t),o=v("lengths",n,e,t),a=t.getTensorArray(s.id);return a.split(o,r),[a.idTensor]}case"TensorArraySizeV3":{const s=v("tensorArrayId",n,e,t),r=t.getTensorArray(s.id);return[pe(r.size(),"int32")]}case"TensorArrayCloseV3":{const s=v("tensorArrayId",n,e,t),r=t.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{const s=v("tensorListId",n,e,t),r=v("index",n,e,t),o=v("tensor",n,e,t),a=t.getTensorList(s.id);return a.setItem(r,o),[a.idTensor]}case"TensorListGetItem":{const s=v("tensorListId",n,e,t),r=v("index",n,e,t),o=v("elementShape",n,e,t),a=v("elementDType",n,e,t);return[t.getTensorList(s.id).getItem(r,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=v("indices",n,e,t),r=v("tensor",n,e,t),o=v("elementShape",n,e,t),a=v("numElements",n,e,t),i=Z3(r,s,o,a);return t.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const s=v("elementShape",n,e,t),r=v("elementDType",n,e,t);let o;n.op==="TensorListReserve"?o="numElements":o="maxNumElements";const a=v(o,n,e,t),i=n.op==="TensorListReserve"?-1:a,l=Y3(s,r,a,i);return t.addTensorList(l),[l.idTensor]}case"TensorListGather":{const s=v("tensorListId",n,e,t),r=v("indices",n,e,t),o=v("elementShape",n,e,t),a=v("elementDType",n,e,t);return[t.getTensorList(s.id).gather(r,a,o)]}case"TensorListStack":{const s=v("tensorListId",n,e,t),r=v("elementShape",n,e,t),o=v("elementDType",n,e,t),a=v("numElements",n,e,t);return[t.getTensorList(s.id).stack(r,o,a)]}case"TensorListFromTensor":{const s=v("tensor",n,e,t),r=v("elementShape",n,e,t),o=v("elementDType",n,e,t),a=X3(s,r,o);return t.addTensorList(a),[a.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const s=v("tensorListId",n,e,t),r=t.getTensorList(s.id),o=v("dtype",n,e,t),a=v("elementShape",n,e,t);return[r.concat(o,a)]}case"TensorListPushBack":{const s=v("tensorListId",n,e,t),r=v("tensor",n,e,t),o=t.getTensorList(s.id);return o.pushBack(r),[o.idTensor]}case"TensorListPopBack":{const s=v("tensorListId",n,e,t),r=v("elementShape",n,e,t),o=v("elementDType",n,e,t);return[t.getTensorList(s.id).popBack(r,o)]}case"TensorListSplit":{const s=v("tensor",n,e,t),r=v("elementShape",n,e,t),o=v("lengths",n,e,t),a=J3(s,o,r);return t.addTensorList(a),[a.idTensor]}case"TensorListLength":{const s=v("tensorListId",n,e,t),r=t.getTensorList(s.id);return[pe(r.size(),"int32")]}case"TensorListResize":{const s=v("tensorListId",n,e,t),r=v("size",n,e,t),a=t.getTensorList(s.id).resize(r);return t.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Nb(n,e,t){const[s,r]=v("fusedOps",n,e,t),o=s==="biasadd",a=!o,i=r==="prelu",l=s==="fusedbatchnorm",u=v("numArgs",n,e,t);if(o){if(i&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&o&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=v("strides",n,e,t),h=Nl(n,e,t),d=v("dataFormat",n,e,t).toUpperCase(),p=v("dilations",n,e,t);let[f,g]=v("args",n,e,t);a&&(g=f,f=void 0);const m=v("leakyreluAlpha",n,e,t);return{stride:c,pad:h,dataFormat:d,dilations:p,biasArg:f,preluArg:g,activationFunc:r,leakyreluAlpha:m}}const ez=(n,e,t,s=_t)=>{switch(n.op){case"Conv1D":{const r=v("stride",n,e,t),o=v("pad",n,e,t),a=v("dataFormat",n,e,t).toUpperCase(),i=v("dilation",n,e,t);return[s.conv1d(v("x",n,e,t),v("filter",n,e,t),r,o,a,i)]}case"Conv2D":{const r=v("strides",n,e,t),o=Nl(n,e,t),a=v("dataFormat",n,e,t).toUpperCase(),i=v("dilations",n,e,t);return[s.conv2d(v("x",n,e,t),v("filter",n,e,t),[r[1],r[2]],o,a,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:r,pad:o,dataFormat:a,dilations:i,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=Nb(n,e,t);return[s.fused.conv2d({x:v("x",n,e,t),filter:v("filter",n,e,t),strides:[r[1],r[2]],pad:o,dataFormat:a,dilations:[i[1],i[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:r,pad:o,dataFormat:a,dilations:i,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=Nb(n,e,t);return[s.fused.depthwiseConv2d({x:v("x",n,e,t),filter:v("filter",n,e,t),strides:[r[1],r[2]],pad:o,dataFormat:a,dilations:[i[1],i[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const r=v("outputShape",n,e,t),o=v("strides",n,e,t),a=Nl(n,e,t);return[s.conv2dTranspose(v("x",n,e,t),v("filter",n,e,t),r,[o[1],o[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const r=v("strides",n,e,t),o=Nl(n,e,t),a=v("dilations",n,e,t),i=v("dataFormat",n,e,t).toUpperCase();return[s.depthwiseConv2d(v("input",n,e,t),v("filter",n,e,t),[r[1],r[2]],o,i,[a[1],a[2]])]}case"Conv3D":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("dataFormat",n,e,t).toUpperCase(),i=v("dilations",n,e,t);return[s.conv3d(v("x",n,e,t),v("filter",n,e,t),[r[1],r[2],r[3]],o,a,[i[1],i[2],i[3]])]}case"AvgPool":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("kernelSize",n,e,t);return[s.avgPool(v("x",n,e,t),[a[1],a[2]],[r[1],r[2]],o)]}case"MaxPool":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("kernelSize",n,e,t);return[s.maxPool(v("x",n,e,t),[a[1],a[2]],[r[1],r[2]],o)]}case"MaxPoolWithArgmax":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("kernelSize",n,e,t),i=v("includeBatchInIndex",n,e,t),{result:l,indexes:u}=s.maxPoolWithArgmax(v("x",n,e,t),[a[1],a[2]],[r[1],r[2]],o,i);return[l,u]}case"AvgPool3D":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("kernelSize",n,e,t);return[s.avgPool3d(v("x",n,e,t),[a[1],a[2],a[3]],[r[1],r[2],r[3]],o)]}case"MaxPool3D":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("kernelSize",n,e,t);return[s.maxPool3d(v("x",n,e,t),[a[1],a[2],a[3]],[r[1],r[2],r[3]],o)]}case"Dilation2D":{const r=v("strides",n,e,t),o=v("pad",n,e,t),a=v("dilations",n,e,t),i=r[1],l=r[2],u=a[1],c=a[2];return[s.dilation2d(v("x",n,e,t),v("filter",n,e,t),[i,l],o,[u,c],"NHWC")]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tz=(n,e,t,s=_t)=>{switch(n.op){case"Fill":{const r=v("shape",n,e,t),o=v("dtype",n,e,t),a=v("value",n,e,t);return[s.fill(r,a,o)]}case"LinSpace":{const r=v("start",n,e,t),o=v("stop",n,e,t),a=v("num",n,e,t);return[s.linspace(r,o,a)]}case"Multinomial":{const r=v("logits",n,e,t),o=v("numSamples",n,e,t),a=v("seed",n,e,t);return[s.multinomial(r,o,a)]}case"OneHot":{const r=v("indices",n,e,t),o=v("depth",n,e,t),a=v("onValue",n,e,t),i=v("offValue",n,e,t),l=v("dtype",n,e,t);return[s.oneHot(r,o,a,i,l)]}case"Ones":return[s.ones(v("shape",n,e,t),v("dtype",n,e,t))];case"OnesLike":return[s.onesLike(v("x",n,e,t))];case"RandomStandardNormal":return[s.randomStandardNormal(v("shape",n,e,t),v("dtype",n,e,t),v("seed",n,e,t))];case"RandomUniform":return[s.randomUniform(v("shape",n,e,t),v("minval",n,e,t),v("maxval",n,e,t),v("dtype",n,e,t))];case"RandomUniformInt":return[s.randomUniformInt(v("shape",n,e,t),v("minval",n,e,t),v("maxval",n,e,t),v("seed",n,e,t))];case"Range":{const r=v("start",n,e,t),o=v("stop",n,e,t),a=v("step",n,e,t);return[s.range(r,o,a,v("dtype",n,e,t))]}case"TruncatedNormal":{const r=v("shape",n,e,t),o=v("mean",n,e,t),a=v("stdDev",n,e,t),i=v("seed",n,e,t);return[s.truncatedNormal(r,o,a,v("dtype",n,e,t),i)]}case"Zeros":return[s.zeros(v("shape",n,e,t),v("dtype",n,e,t))];case"ZerosLike":return[s.zerosLike(v("x",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lh(n,e,t){const s=v("boxes",n,e,t),r=v("scores",n,e,t),o=v("maxOutputSize",n,e,t),a=v("iouThreshold",n,e,t),i=v("scoreThreshold",n,e,t),l=v("softNmsSigma",n,e,t);return{boxes:s,scores:r,maxOutputSize:o,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}}const nz=async(n,e,t,s,r=_t)=>{switch(n.op){case"NonMaxSuppressionV5":{const{boxes:o,scores:a,maxOutputSize:i,iouThreshold:l,scoreThreshold:u,softNmsSigma:c}=Lh(n,e,t),h=await r.image.nonMaxSuppressionWithScoreAsync(o,a,i,l,u,c);return[h.selectedIndices,h.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:o,scores:a,maxOutputSize:i,iouThreshold:l,scoreThreshold:u}=Lh(n,e,t),c=v("padToMaxOutputSize",n,e,t),h=await r.image.nonMaxSuppressionPaddedAsync(o,a,i,l,u,c);return[h.selectedIndices,h.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:o,scores:a,maxOutputSize:i,iouThreshold:l,scoreThreshold:u}=Lh(n,e,t);return[await r.image.nonMaxSuppressionAsync(o,a,i,l,u)]}case"Where":{const o=r.cast(v("condition",n,e,t),"bool"),a=[await r.whereAsync(o)];return o.dispose(),a}case"ListDiff":return r.setdiff1dAsync(v("x",n,e,t),v("y",n,e,t));default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sz=(n,e,t,s=_t)=>{switch(n.op){case"LowerBound":{const r=v("sortedSequence",n,e,t),o=v("values",n,e,t);return[s.lowerBound(r,o)]}case"TopKV2":{const r=v("x",n,e,t),o=v("k",n,e,t),a=v("sorted",n,e,t),i=s.topk(r,o,a);return[i.values,i.indices]}case"UpperBound":{const r=v("sortedSequence",n,e,t),o=v("values",n,e,t);return[s.upperBound(r,o)]}case"Unique":{const r=v("x",n,e,t),o=s.unique(r);return[o.values,o.indices]}case"UniqueV2":{const r=v("x",n,e,t),o=v("axis",n,e,t),a=s.unique(r,o);return[a.values,a.indices]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rz=(n,e,t,s=_t)=>{switch(n.op){case"Const":return e[n.name];case"PlaceholderWithDefault":const r=v("default",n,e,t);return[Ct(n.name,e,t)||r];case"Placeholder":return[Ct(n.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const c=v("x",n,e,t);return[bs(c)]}case"IdentityN":return v("x",n,e,t).map(c=>bs(c));case"Snapshot":const o=v("x",n,e,t);return[bs(o)];case"Shape":return[s.tensor1d(v("x",n,e,t).shape,"int32")];case"ShapeN":return v("x",n,e,t).map(c=>s.tensor1d(c.shape));case"Size":return[s.scalar(v("x",n,e,t).size,"int32")];case"Rank":return[s.scalar(v("x",n,e,t).rank,"int32")];case"NoOp":return[s.scalar(1)];case"Print":const a=v("x",n,e,t),i=v("data",n,e,t),l=v("message",n,e,t),u=v("summarize",n,e,t);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let c=0;ce.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return pe(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const s=await e.data();return this.tensorMap.forEach(r=>r.dispose()),this.tensorMap.clear(),z(()=>{const r=Rn(t),o=s.length,a=r.length;I(o===a,()=>`The number of elements doesn't match, keys has ${o} elements, the values has ${a} elements.`);for(let i=0;i{const r=[];for(let o=0;o{switch(n.op){case"HashTable":case"HashTableV2":{const r=s.getHashTableHandleByName(n.name);if(r!=null)return[r];{const o=v("keyDType",n,e,t),a=v("valueDType",n,e,t),i=new oz(o,a);return s.addHashTable(n.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const r=v("tableHandle",n,e,t,s),o=v("keys",n,e,t),a=v("values",n,e,t);return[await s.getHashTableById(r.id).import(o,a)]}case"LookupTableFind":case"LookupTableFindV2":{const r=v("tableHandle",n,e,t,s),o=v("keys",n,e,t),a=v("defaultValue",n,e,t);return[await s.getHashTableById(r.id).find(o,a)]}case"LookupTableSize":case"LookupTableSizeV2":{const r=v("tableHandle",n,e,t,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iz=(n,e,t,s=_t)=>{switch(n.op){case"ResizeBilinear":{const r=v("images",n,e,t),o=v("size",n,e,t),a=v("alignCorners",n,e,t),i=v("halfPixelCenters",n,e,t);return[s.image.resizeBilinear(r,[o[0],o[1]],a,i)]}case"ResizeNearestNeighbor":{const r=v("images",n,e,t),o=v("size",n,e,t),a=v("alignCorners",n,e,t),i=v("halfPixelCenters",n,e,t);return[s.image.resizeNearestNeighbor(r,[o[0],o[1]],a,i)]}case"CropAndResize":{const r=v("image",n,e,t),o=v("boxes",n,e,t),a=v("boxInd",n,e,t),i=v("cropSize",n,e,t),l=v("method",n,e,t),u=v("extrapolationValue",n,e,t);return[s.image.cropAndResize(r,o,a,i,l,u)]}case"ImageProjectiveTransformV3":{const r=v("images",n,e,t),o=v("transforms",n,e,t),a=v("outputShape",n,e,t),i=v("fillValue",n,e,t),l=v("interpolation",n,e,t),u=v("fillMode",n,e,t);return[s.image.transform(r,o,l.toLowerCase(),u.toLowerCase(),i,a)]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lz=(n,e,t,s=_t)=>{switch(n.op){case"Equal":return[s.equal(v("a",n,e,t),v("b",n,e,t))];case"NotEqual":return[s.notEqual(v("a",n,e,t),v("b",n,e,t))];case"Greater":return[s.greater(v("a",n,e,t),v("b",n,e,t))];case"GreaterEqual":return[s.greaterEqual(v("a",n,e,t),v("b",n,e,t))];case"Less":return[s.less(v("a",n,e,t),v("b",n,e,t))];case"LessEqual":return[s.lessEqual(v("a",n,e,t),v("b",n,e,t))];case"LogicalAnd":return[s.logicalAnd(v("a",n,e,t),v("b",n,e,t))];case"LogicalNot":return[s.logicalNot(v("a",n,e,t))];case"LogicalOr":return[s.logicalOr(v("a",n,e,t),v("b",n,e,t))];case"Select":case"SelectV2":return[s.where(v("condition",n,e,t),v("a",n,e,t),v("b",n,e,t))];case"BitwiseAnd":return[s.bitwiseAnd(v("a",n,e,t),v("b",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uz=(n,e,t,s=_t)=>{switch(n.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[s.matMul(v("a",n,e,t),v("b",n,e,t),v("transposeA",n,e,t),v("transposeB",n,e,t))];case"Einsum":return[s.einsum(v("equation",n,e,t),...v("tensors",n,e,t))];case"Transpose":return[s.transpose(v("x",n,e,t),v("perm",n,e,t))];case"_FusedMatMul":const[r,o]=v("fusedOps",n,e,t),a=r==="biasadd",i=o==="prelu",l=v("numArgs",n,e,t),u=v("leakyreluAlpha",n,e,t);if(a){if(i&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=v("args",n,e,t);return[s.fused.matMul({a:v("a",n,e,t),b:v("b",n,e,t),transposeA:v("transposeA",n,e,t),transposeB:v("transposeB",n,e,t),bias:c,activation:o,preluActivationWeights:h,leakyreluAlpha:u})];case"MatrixBandPart":return[s.linalg.bandPart(v("a",n,e,t),v("numLower",n,e,t),v("numUpper",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cz=(n,e,t,s=_t)=>{switch(n.op){case"EuclideanNorm":return[s.euclideanNorm(v("x",n,e,t),v("axis",n,e,t),v("keepDims",n,e,t))];case"FusedBatchNorm":case"FusedBatchNormV2":return[s.batchNorm(v("x",n,e,t),v("mean",n,e,t),v("variance",n,e,t),v("offset",n,e,t),v("scale",n,e,t),v("epsilon",n,e,t))];case"FusedBatchNormV3":return[s.batchNorm(v("x",n,e,t),v("mean",n,e,t),v("variance",n,e,t),v("offset",n,e,t),v("scale",n,e,t),v("epsilon",n,e,t))];case"LRN":return[s.localResponseNormalization(v("x",n,e,t),v("radius",n,e,t),v("bias",n,e,t),v("alpha",n,e,t),v("beta",n,e,t))];case"Softmax":return[s.softmax(v("x",n,e,t))];case"LogSoftmax":return[s.logSoftmax(v("x",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hz=(n,e,t,s=_t)=>{switch(n.op){case"RaggedGather":{const{outputNestedSplits:r,outputDenseValues:o}=s.raggedGather(v("paramsNestedSplits",n,e,t),v("paramsDenseValues",n,e,t),v("indices",n,e,t),v("outputRaggedRank",n,e,t));return r.concat(o)}case"RaggedRange":{const{rtNestedSplits:r,rtDenseValues:o}=s.raggedRange(v("starts",n,e,t),v("limits",n,e,t),v("splits",n,e,t));return[r,o]}case"RaggedTensorToTensor":return[s.raggedTensorToTensor(v("shape",n,e,t),v("values",n,e,t),v("defaultValue",n,e,t),v("rowPartitionTensors",n,e,t),v("rowPartitionTypes",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dz=(n,e,t,s=_t)=>{switch(n.op){case"Max":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.max(v("x",n,e,t),i,l)]}case"Mean":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.mean(v("x",n,e,t),i,l)]}case"Min":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.min(v("x",n,e,t),i,l)]}case"Sum":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.sum(v("x",n,e,t),i,l)]}case"All":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.all(v("x",n,e,t),i,l)]}case"Any":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.any(v("x",n,e,t),i,l)]}case"ArgMax":{const i=v("axis",n,e,t);return[s.argMax(v("x",n,e,t),i)]}case"ArgMin":{const i=v("axis",n,e,t);return[s.argMin(v("x",n,e,t),i)]}case"Prod":{const i=v("axis",n,e,t),l=v("keepDims",n,e,t);return[s.prod(v("x",n,e,t),i,l)]}case"Cumprod":{const i=v("axis",n,e,t),l=v("exclusive",n,e,t),u=v("reverse",n,e,t);return[s.cumprod(v("x",n,e,t),i,l,u)]}case"Cumsum":{const i=v("axis",n,e,t),l=v("exclusive",n,e,t),u=v("reverse",n,e,t);return[s.cumsum(v("x",n,e,t),i,l,u)]}case"Bincount":const r=v("x",n,e,t),o=v("weights",n,e,t),a=v("size",n,e,t);return[s.bincount(r,o,a)];case"DenseBincount":{const i=v("x",n,e,t),l=v("weights",n,e,t),u=v("size",n,e,t),c=v("binaryOutput",n,e,t);return[s.denseBincount(i,l,u,c)]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pz=(n,e,t,s=_t)=>{switch(n.op){case"ConcatV2":case"Concat":{const r=v("n",n,e,t),o=v("axis",n,e,t);let a=v("tensors",n,e,t);return a=a.slice(0,r),[s.concat(a,o)]}case"Gather":{const r=v("x",n,e,t),o=v("indices",n,e,t);return[s.gather(r,s.cast(o,"int32"),0)]}case"GatherV2":{const r=v("axis",n,e,t),o=v("batchDims",n,e,t),a=v("x",n,e,t),i=v("indices",n,e,t);return[s.gather(a,s.cast(i,"int32"),r,o)]}case"Reverse":{const r=v("dims",n,e,t),o=[];for(let i=0;i{const r=v("axis",n,e,t),o=v("tensors",n,e,t),a=o[0].shape,i=s.squeeze(o[0]).shape,l=o.map(u=>{const c=Ce(u.shape,a);if(!c&&!Ce(s.squeeze(u).shape,i))throw new Error("the input tensors shape does not match");return c?u:s.reshape(u,a)});return[s.stack(l,r)]});case"Unpack":{const r=v("axis",n,e,t),o=v("tensor",n,e,t);return s.unstack(o,r)}case"Tile":{const r=v("reps",n,e,t);return[s.tile(v("x",n,e,t),r)]}case"Split":case"SplitV":{const r=v("axis",n,e,t),o=v("numOrSizeSplits",n,e,t),a=v("x",n,e,t);return s.split(a,o,r)}case"ScatterNd":{const r=v("indices",n,e,t),o=v("values",n,e,t),a=v("shape",n,e,t);return[s.scatterND(r,o,a)]}case"GatherNd":{const r=v("x",n,e,t),o=v("indices",n,e,t);return[s.gatherND(r,o)]}case"SparseToDense":{const r=v("sparseIndices",n,e,t),o=v("outputShape",n,e,t),a=v("sparseValues",n,e,t),i=v("defaultValue",n,e,t);return[s.sparseToDense(r,a,o,a.dtype===i.dtype?i:s.cast(i,a.dtype))]}case"TensorScatterUpdate":{const r=v("indices",n,e,t),o=v("values",n,e,t),a=v("tensor",n,e,t);return[s.tensorScatterUpdate(a,r,o)]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fz=(n,e,t,s=_t)=>{switch(n.op){case"SparseFillEmptyRows":{const{outputIndices:r,outputValues:o,emptyRowIndicator:a,reverseIndexMap:i}=s.sparse.sparseFillEmptyRows(v("indices",n,e,t),v("values",n,e,t),v("denseShape",n,e,t),v("defaultValue",n,e,t));return[r,o,a,i]}case"SparseReshape":{const{outputIndices:r,outputShape:o}=s.sparse.sparseReshape(v("inputIndices",n,e,t),v("inputShape",n,e,t),v("newShape",n,e,t));return[r,o]}case"SparseSegmentMean":return[s.sparse.sparseSegmentMean(v("data",n,e,t),v("indices",n,e,t),v("segmentIds",n,e,t))];case"SparseSegmentSum":return[s.sparse.sparseSegmentSum(v("data",n,e,t),v("indices",n,e,t),v("segmentIds",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mz=(n,e,t,s=_t)=>{switch(n.op){case"FFT":return[s.fft(v("x",n,e,t))];case"IFFT":return[s.ifft(v("x",n,e,t))];case"RFFT":return[s.rfft(v("x",n,e,t))];case"IRFFT":return[s.irfft(v("x",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gz=(n,e,t,s=_t)=>{switch(n.op){case"StaticRegexReplace":return[s.string.staticRegexReplace(v("input",n,e,t),v("pattern",n,e,t),v("rewrite",n,e,t),v("replaceGlobal",n,e,t))];case"StringNGrams":{const{nGrams:r,nGramsSplits:o}=s.string.stringNGrams(v("data",n,e,t),v("dataSplits",n,e,t),v("separator",n,e,t),v("nGramWidths",n,e,t),v("leftPad",n,e,t),v("rightPad",n,e,t),v("padWidth",n,e,t),v("preserveShortSequences",n,e,t));return[r,o]}case"StringSplit":{const{indices:r,values:o,shape:a}=s.string.stringSplit(v("input",n,e,t),v("delimiter",n,e,t),v("skipEmpty",n,e,t));return[r,o,a]}case"StringToHashBucketFast":return[s.string.stringToHashBucketFast(v("input",n,e,t),v("numBuckets",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yz=(n,e,t,s=_t)=>{switch(n.op){case"Cast":return[s.cast(v("x",n,e,t),v("dtype",n,e,t))];case"ExpandDims":{const r=v("axis",n,e,t);return[s.expandDims(v("x",n,e,t),r)]}case"Squeeze":{const r=v("axis",n,e,t);return[s.squeeze(v("x",n,e,t),r)]}case"Reshape":return[s.reshape(v("x",n,e,t),v("shape",n,e,t))];case"EnsureShape":return[s.ensureShape(v("x",n,e,t),v("shape",n,e,t))];case"MirrorPad":return[s.mirrorPad(v("x",n,e,t),v("padding",n,e,t),v("mode",n,e,t))];case"PadV2":case"Pad":return[s.pad(v("x",n,e,t),v("padding",n,e,t),v("constantValue",n,e,t))];case"SpaceToBatchND":{const r=v("blockShape",n,e,t),o=v("paddings",n,e,t);return[s.spaceToBatchND(v("x",n,e,t),r,o)]}case"BatchToSpaceND":{const r=v("blockShape",n,e,t),o=v("crops",n,e,t);return[s.batchToSpaceND(v("x",n,e,t),r,o)]}case"DepthToSpace":{const r=v("blockSize",n,e,t),o=v("dataFormat",n,e,t).toUpperCase();return[s.depthToSpace(v("x",n,e,t),r,o)]}case"BroadcastTo":return[s.broadcastTo(v("x",n,e,t),v("shape",n,e,t))];case"BroadcastArgs":return[s.broadcastArgs(v("s0",n,e,t),v("s1",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cb(n,e,t,s,r=z){const o=((a,i,l)=>{switch(a.category){case"arithmetic":return r(()=>j3(a,i,l));case"basic_math":return r(()=>q3(a,i,l));case"control":return Q3(a,i,l);case"convolution":return r(()=>ez(a,i,l));case"creation":return r(()=>tz(a,i,l));case"dynamic":return nz(a,i,l);case"evaluation":return r(()=>sz(a,i,l));case"image":return r(()=>iz(a,i,l));case"graph":return r(()=>rz(a,i,l));case"logical":return r(()=>lz(a,i,l));case"matrices":return r(()=>uz(a,i,l));case"normalization":return r(()=>cz(a,i,l));case"ragged":return r(()=>hz(a,i,l));case"reduction":return r(()=>dz(a,i,l));case"slice_join":return r(()=>pz(a,i,l));case"sparse":return r(()=>fz(a,i,l));case"spectral":return r(()=>mz(a,i,l));case"string":return r(()=>gz(a,i,l));case"transformation":return r(()=>yz(a,i,l));case"hash_table":return az(a,i,l,s);case"custom":const u=av(a.op);if(u&&u.customExecutor)return u.customExecutor(new H3(a,i,l));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(n,e,t);return $s(o)?o.then(a=>[].concat(a)):[].concat(o)}class kb{constructor(e={},t={},s={},r={},o){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=s,this.functionMap=r,this.parseNodeNameCache=o,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;tt.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tb(n,e,t,s){const r=new Set,o=[];let a=null,i=null;const l=new Set,u=new Set(Object.keys(n).map(d=>nn(d)[0]));s=s||[];const c=new Set(s.map(d=>nn(d.name)[0])),h=[...e];for(;h.length>0;){const d=h.pop();if((Sr(d)||Nz(d)||Cz(d))&&a==null&&(a=d,i=a.children.map(p=>p.name).filter(p=>r.has(p))),r.add(d.name),t[d.name]==null&&!u.has(d.name)&&!c.has(d.name)){if(d.inputs.length===0){o.push(d.name);continue}d.inputs.forEach(p=>{l.has(p.name)||(l.add(p.name),h.push(p))})}}return{inputs:n,outputs:e,usedNodes:r,missingInputs:o,dynamicNode:a,syncInputs:i}}function bz(n,e){const{usedNodes:t,inputs:s}=e,r=Object.keys(s).map(m=>nn(m)[0]).map(m=>n.nodes[m]),o=n.initNodes||[],a=m=>t.has(typeof m=="string"?m:m.name);function i(m){return[...new Map(m.map(y=>[y.name,y])).values()]}const l=i([...r,...n.weights,...o]).filter(a),u=i([...l,...Object.values(n.nodes)]).filter(a),c=new Map(u.map(m=>[m.name,m])),h={};for(const m of u){h[m.name]=h[m.name]||0;for(const y of m.children)a(y)||(h[y.name]=Number.POSITIVE_INFINITY),h[y.name]=(h[y.name]||0)+1}const d=Object.entries(h).filter(([,m])=>m===0).map(([m])=>m),p=[...d];for(;d.length>0;){const m=d.pop(),y=c.get(m);for(const b of y.children.filter(a))--h[b.name]===0&&(p.push(b.name),d.push(b.name))}const f=p.map(m=>c.get(m)),g=xz(f,l);return wz(g,l),g}function xz(n,e){const t=new Map(n.map(a=>[a.name,a])),s=e.map(a=>a.name),r=new Set(s);for(;s.length>0;){const a=s.pop(),i=t.get(a);for(const l of i.children)!t.has(l.name)||r.has(l.name)||(r.add(l.name),s.push(l.name))}return n.filter(a=>r.has(a.name))}class ll extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}function wz(n,e){const t=new Map(n.map((i,l)=>[i.name,l])),s=new Set(e.map(i=>i.name)),r=i=>s.has(typeof i=="string"?i:i.name),o=new Set(n.map(i=>i.name)),a=i=>o.has(typeof i=="string"?i:i.name);for(const i of n){for(const l of i.children.filter(a)){if(!t.has(l.name))throw new ll(`Child ${l.name} of node ${i.name} is unreachable.`);if(t.get(i.name)>t.get(l.name))throw new ll(`Node ${i.name} is scheduled to run after its child ${l.name}.`)}if(!r(i))for(const l of i.inputs){if(!t.has(l.name))throw new ll(`Input ${l.name} of node ${i.name} is unreachable.`);if(t.get(l.name)>t.get(i.name))throw new ll(`Node ${i.name} is scheduled to run before its input ${l.name}.`)}}}function vz(n){const e=new Map(n.map((i,l)=>[i.name,l])),t=Number.MAX_SAFE_INTEGER,s=n.map((i,l)=>Sr(i)?t:l),r=i=>{const l=s[e.get(i.name)];return l??-1},o=n.map((i,l)=>i.children.map(r).reduce((u,c)=>Math.max(u,c),s[l])),a=new Map;for(let i=0;ie[s].map(r=>r.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(s=>{this._functionExecutorMap[s]=new Ql(e.functions[s],this)})}getCompilationKey(e,t){const s=e.map(o=>o.name).sort(),r=t.map(o=>o.name).sort();return s.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const s=Tb(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:o,syncInputs:a}=s;if(o!=null)throw new Error(`This execution contains the node '${o.name}', which has the dynamic op '${o.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){const u=t.map(h=>h.name),c=Object.keys(e);throw new Error(`Cannot compute the outputs [${u}] from the provided inputs [${c}]. Missing the following inputs: [${r}]`)}const i=bz(this.graph,s),l=vz(i);return{orderedNodes:i,nodeLiveUntilMap:l}}cloneAndKeepTensor(e){if(e==null)return null;const t=e.clone();return bt(t),t}cloneTensorList(e){return e?e.map(s=>this.cloneAndKeepTensor(s)):null}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([t,s])=>[t,this.cloneTensorList(s)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const s=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=s.map(d=>this.graph.nodes[nn(d)[0]]),o=t.map(d=>nn(d)[0]),a=new Set(o);let i=o.map(d=>this.graph.nodes[d]);i.length===0&&(i=this._outputs);const l=this.getCompilationKey(r,i);let u=this.compiledMap.get(l);u==null&&(u=this.compile(e,i),this.compiledMap.set(l,u));try{this.keepIntermediateTensors=B().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const c={},h={};return z(()=>{const d=new kb(this.weightMap,c,h,this.functionExecutorMap,this.parseNodeNameCache),p=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(y=>{const[b,w]=nn(y,d),x=[];x[w]=e[y],p[b]=x,this.keepIntermediateTensors&&(this.clonedTensorsMap[b]=this.cloneTensorList(x))});const f=this.getFrozenTensorIds(p),{orderedNodes:g,nodeLiveUntilMap:m}=u;for(const y of g){if(p[y.name])continue;const b=Cb(y,p,d,this._resourceManager);if($s(b))throw new Error(`The execution of the op '${y.op}' returned a promise. Please use model.executeAsync() instead.`);p[y.name]=b,this.keepIntermediateTensors&&(this.clonedTensorsMap[y.name]=this.cloneTensorList(b)),this.checkTensorForDisposalWithNodeLiveUntilInfo(y,p,d,f,a,m.get(y.name))}return this.parent==null&&d.dispose(f),t.map(y=>Ct(y,p,d))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(s=>e[s]).map(s=>s.map(r=>r.id)));return new Set(t)}checkTensorForDisposal(e,t,s,r,o,a,i){if(!(Sr(t)||a.has(e))){for(const l of s[e])l!=null&&(i[l.id]=(i[l.id]||0)+t.children.length);for(const l of t.inputs){if(Sr(l))continue;const u=vb(l.name,s,r);if(u!=null)for(const c of u){if(!c||c.kept||o.has(c.id))continue;const h=i[c.id];h===1?(c.dispose(),delete i[c.id]):h!=null&&i[c.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,s,r,o,a){function i(l){return Sr(l)||o.has(l.name)}if(!(Sr(e)||a==null))for(const l of a){if(i(l))continue;const u=vb(l.name,t,s);for(const c of u)!c||c.kept||r.has(c.id)||c.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,s=!1,r={},o={}){this.disposeIntermediateTensors(),s||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=B().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const a=new kb(this.weightMap,r,o,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,s),l=t.map(d=>Ct(d,i,a)),u=l.map(d=>d.id),c=Object.keys(e).map(d=>e[d].id),h=new Set([...u,...c,...this.weightIds]);return Object.values(i).forEach(d=>{d.forEach(p=>{p&&!p.isDisposed&&!h.has(p.id)&&p.dispose()})}),this.parent==null&&a.dispose(h),l}async executeFunctionAsync(e,t,s){const r=e.reduce((o,a,i)=>(o[this.inputs[i].name]=a,o),{});return this._executeAsync(r,this.outputNodes,!0,t,s)}async executeWithControlFlow(e,t,s,r){const o=Object.keys(e),a=o.map(x=>this.graph.nodes[nn(x)[0]]),i=s.map(x=>nn(x)[0]),l=new Set(i);let u=i.map(x=>this.graph.nodes[x]);u.length===0&&(u=this._outputs);const{usedNodes:c,missingInputs:h,dynamicNode:d,syncInputs:p}=Tb(e,u,this.weightMap,this._initNodes),f=[...a,...this.graph.weights,...this._initNodes||[]].map(x=>({node:x,contexts:t.currentContext})),g=Object.assign({},this.weightMap);Object.keys(e).forEach(x=>{const[$,C]=nn(x),E=[];E[C]=e[x],g[$]=E});const m={},y=this.getFrozenTensorIds(g),b={};for(;f.length>0;){const x=this.processStack(a,f,t,g,b,y,l,m,c);await Promise.all(x)}d==null&&!r&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const w=u.filter(x=>!Sr(x)&&!Ct(x.name,g,t)).map(x=>x.name);if(w.length>0){let x="";throw d!=null&&(x=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${w}] from the provided inputs [${o}]. Consider providing the following inputs: [${h}]. ${x}`)}return g}processStack(e,t,s,r,o,a,i,l,u){const c=[];for(;t.length>0;){const h=t.pop();s.currentContext=h.contexts;let d="";if(h.node.op==="Enter"&&v("isConstant",h.node,r,s)&&([d]=ys(h.node.name,s)),r[h.node.name]==null){const p=Cb(h.node,r,s,this._resourceManager);d||([d]=ys(h.node.name,s));const f=s.currentContext;$s(p)?c.push(p.then(g=>(r[d]=g,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(g)),s.currentContext=f,this.checkTensorForDisposal(d,h.node,r,s,a,i,l),this.processChildNodes(h.node,t,s,r,o,u),g))):(r[d]=p,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(p)),this.checkTensorForDisposal(d,h.node,r,s,a,i,l),this.processChildNodes(h.node,t,s,r,o,u))}else this.processChildNodes(h.node,t,s,r,o,u)}return c}processChildNodes(e,t,s,r,o,a){e.children.forEach(i=>{const[l]=ys(i.name,s);o[l]||!a.has(i.name)||(i.op==="Merge"?i.inputNames.some(u=>!!Ct(u,r,s))&&(o[l]=!0,t.push({contexts:s.currentContext,node:i})):i.inputNames.every(u=>!!Ct(u,r,s))&&(o[l]=!0,t.push({contexts:s.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const s=e[t],[r]=nn(t),o=this.graph.nodes[r];if(o.attrParams.shape&&o.attrParams.shape.value){const a=o.attrParams.shape.value,i=a.length===s.shape.length&&s.shape.every((l,u)=>a[u]===-1||a[u]===l);I(i,()=>`The shape of dict['${o.name}'] provided in model.execute(dict) must be [${a}], but was [${s.shape}]`)}o.attrParams.dtype&&o.attrParams.dtype.value&&I(s.dtype===o.attrParams.dtype.value,()=>`The dtype of dict['${o.name}'] provided in model.execute(dict) must be ${o.attrParams.dtype.value}, but was ${s.dtype}`)})}mapInputs(e){var t,s;const r={};for(const o in e){const a=(s=(t=this._signature)===null||t===void 0?void 0:t.inputs)===null||s===void 0?void 0:s[o];a!=null?r[a.name]=e[o]:r[o]=e[o]}return r}checkInputs(e){const t=Object.keys(e).filter(s=>{const[r]=nn(s);return this.graph.nodes[r]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{var s,r;const o=(r=(s=this._signature)===null||s===void 0?void 0:s.outputs)===null||r===void 0?void 0:r[t];return o!=null?o.name:t},{})}checkOutputs(e){e.forEach(t=>{const[s]=nn(t);if(!this.graph.nodes[s])throw new Error(`The output '${t}' is not found in the graph`)})}}class kz{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tz="?tfjs-format=file",Ez="model.json";class uv{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},s=m0){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=s,t==null&&(this.loadOptions={}),this.resourceManager=new kz}findIOHandler(){const e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return $s(e)?e.then(t=>t.getWeightStream==null?this.loadSync(t):this.loadStreaming(t)):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(e.getWeightStream==null)throw new Error("Model artifacts missing streamWeights function");const t=await Px(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const s=this.artifacts.modelTopology;let r=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){const o=this.artifacts.userDefinedMetadata;o.signature!=null&&(r=o.signature),o.structuredOutputKeys!=null&&(this.structuredOutputKeys=o.structuredOutputKeys)}if(this.signature=r,this.version=`${s.versions.producer}.${s.versions.minConsumer}`,this.executor=new Ql($b.Instance.transformGraph(s,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){const o=$b.Instance.transformGraph(e.modelInitializer);this.initializer=new Ql(o),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if(typeof e=="string"){const s=this.io.getSaveHandlers(e);if(s.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(s.length>1)throw new Error(`Found more than one (${s.length}) save handlers for URL '${e}'`);e=s[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t=e instanceof Re?[e]:e,s={};return t.forEach((r,o)=>s[this.structuredOutputKeys[o]]=r),s}return e}predict(e,t){const s=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(s)}async predictAsync(e,t){const s=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(s)}normalizeInputs(e){var t;if(!(e instanceof Re)&&!Array.isArray(e)){const o=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(o!=null)for(const a in o){const i=o[a];i.resourceId!=null&&(e[a]=this.resourceIdToCapturedInput[i.resourceId])}return e}e=Array.isArray(e)?e:[e];const s=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+s!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-s} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce((o,a)=>{var i,l,u;const c=(u=(l=(i=this.signature)===null||i===void 0?void 0:i.inputs)===null||l===void 0?void 0:l[a])===null||u===void 0?void 0:u.resourceId;return c!=null?o[a]=this.resourceIdToCapturedInput[c]:o[a]=e[r++],o},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,s=Object.keys(t);for(let r=0;r1?s:s[0]}async executeAsync(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const s=await this.executor.executeAsync(e,t);return s.length>1?s:s[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,s)=>(t[s]=[e[s]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&be(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function t9(n,e={},t=m0){if(n==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");e==null&&(e={}),e.fromTFHub&&typeof n=="string"&&(n=Az(n));const s=new uv(n,e,t);return await s.load(),s}function n9(n){if(n==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let e;if(n instanceof Array){const[s,r]=n;if(!s)throw new Error("modelJSON must be the first element of the array");if(!r||!(r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in s))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in s))throw new Error("Model JSON is missing 'weightsManifest'");const o=Ml(s.weightsManifest),a=nf(s,o,r);e=Wl(a)}else if("load"in n)e=n;else if("modelTopology"in n&&"weightSpecs"in n&&"weightData"in n)e=Wl(n);else throw new Error("Unknown model format");const t=new uv(e);return t.load(),t}function Az(n){return n.endsWith("/")||(n=n+"/"),`${n}${Ez}${Tz}`}/** @license See the LICENSE file. */const Rz="4.22.0";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */function Dz(n,e){return eu(n,e)}function eu(n,e,t=new Map,s=new Set){if(n==null)return null;if(typeof Blob=="function"&&n instanceof Blob)return n.slice();if(s.has(n))throw new Error("Circular references are not supported.");if(t.has(n))return t.get(n);const r=e(n);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(ko(n)){const o=Array.isArray(n)?[]:{};s.add(n);for(const a in n){const i=n[a],l=eu(i,e,t,s);o[a]=l}return s.delete(n),n.__proto__&&(o.__proto__=n.__proto__),o}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return t.set(n,r.value),r.value}function Oz(n,e=hv){return cv(n,e)}function cv(n,e,t=new Set){const s=n[0];if(t.has(s))throw new Error("Circular references are not supported.");const r=e(n);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(ko(s)){const o=Array.isArray(s)?[]:{};t.add(s);for(const a in s){const i=n.map(u=>u[a]),l=cv(i,e,t);o[a]=l}return t.delete(s),o}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return r.value}function hv(n){return n===null?null:ko(n[0])?{value:null,recurse:!0}:{value:n,recurse:!1}}async function dv(n,e){const t=new Map;eu(n,e,t);for(const r of Array.from(t.keys())){const o=t.get(r);if($s(o)){const a=await o;t.set(r,a)}}return eu(n,e,t)}function ko(n){let e=!1;if(B().get("IS_BROWSER"))e=n instanceof TextDecoder;else{const{StringDecoder:t}=require("string_decoder");e=n instanceof t}return n!=null&&!ArrayBuffer.isView(n)&&(Array.isArray(n)||typeof n=="object"&&!(n instanceof Re)&&!(n instanceof Promise)&&!e)}function _z(n){return n==null||Fz(n)||Array.isArray(n)||typeof n=="object"&&n instanceof Re||ut(n)}function Fz(n){return n===null||typeof n!="object"&&typeof n!="function"}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */function Lz(n){return Dz(n,Pz)}function Pz(n){return n instanceof Re?{value:n.clone(),recurse:!1}:ko(n)?{value:null,recurse:!0}:{value:n,recurse:!1}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class pv{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),s=this.get(t);return this.set(t,this.pop()),s}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class dh extends pv{constructor(){super(dh.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=this.capacity*2,t=new Array(e),s=this.length();for(let r=0;rt===!0)}rowMajorBatch(e,t=!0){return new Hz(this,e,t)}columnMajorBatch(e,t=!0,s=hv){return this.rowMajorBatch(e,t).map(o=>Oz(o,s))}concatenate(e,t){return new mv(fv([this,e]),t)}take(e){return e<0||e==null?this:new Gz(this,e)}skip(e){return e<0||e==null?this:new Uz(this,e)}prefetch(e){return new gv(this,e)}shuffle(e,t){return new Zz(this,e,t)}serial(){return new Wz(this)}}class Bz extends vt{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:Lz(e),done:!1}}}class Vz extends vt{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class Wz extends vt{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}}class Uz extends vt{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class Hz extends vt{constructor(e,t,s=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=s,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){const e=[];for(;e.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class jz extends vt{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;be(e.value)}}}class qz extends vt{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Is(e.value),s=this.transform(e.value),r=Is(s);for(const o of t)fc(o,r)||o.dispose();return{value:s,done:!1}}}class Kz extends vt{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class Eb extends vt{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Is(e.value),s=await this.transform(e.value),r=Is(s);for(const o of t)fc(o,r)||o.dispose();return{value:s,done:!1}}}class Gg extends vt{constructor(){super(),this.outputQueue=new dh,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class Xz extends Gg{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=Is(e.value),s=this.transform(e.value),r=Is(s);this.outputQueue.pushAll(s);for(const o of t)fc(o,r)||o.dispose();return!0}}class mv extends vt{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){const s=await this.moreIterators.next();if(s.done)return{value:null,done:!0};this.iterator=s.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var Gs;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(Gs||(Gs={}));class Yz extends vt{constructor(e,t=Gs.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,s=0;function r(a){return a instanceof vt?{value:a.next().then(l=>(t++,l.done&&s++,l.value)),recurse:!1}:{value:null,recurse:!0}}const o=await dv(this.iterators,r);if(t===s)return{value:null,done:!0};if(s>0)switch(this.mismatchMode){case Gs.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Gs.SHORTEST:return{value:null,done:!0};case Gs.LONGEST:}return this.count++,{value:o,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class gv extends vt{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new pv(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class Zz extends gv{constructor(e,t,s){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=_o.alea(s||Nt().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class Wo{constructor(){this.size=null}batch(e,t=!0){const s=this;I(e>0,()=>`batchSize needs to be positive, but it is + ${e}`);let r;return this.size===1/0||this.size==null?r=this.size:t?r=Math.ceil(this.size/e):r=Math.floor(this.size/e),tn(async()=>(await s.iterator()).columnMajorBatch(e,t,eM),r)}concatenate(e){const t=this;let s;return this.size===1/0||e.size===1/0?s=1/0:this.size!=null&&e.size!=null?s=this.size+e.size:s=null,tn(async()=>(await t.iterator()).concatenate(await e.iterator()),s)}filter(e){const t=this;let s;return this.size===1/0?s=1/0:s=null,tn(async()=>(await t.iterator()).filter(r=>z(()=>e(r))),s)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return tn(async()=>(await t.iterator()).map(s=>z(()=>e(s))),this.size)}mapAsync(e){const t=this;return tn(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return tn(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let s;return this.size!=null&&e>0?s=this.size*e:e===0?s=0:this.size!=null&&(e===void 0||e<0)?s=1/0:s=null,tn(async()=>{const r=Ug(async()=>({value:await t.iterator(),done:!1}));return zz(r.take(e))},s)}skip(e){const t=this;let s;return this.size!=null&&e>=0&&this.size>=e?s=this.size-e:this.size!=null&&(this.size(await t.iterator()).skip(e),s)}shuffle(e,t,s=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const r=this,o=_o.alea(t||Nt().toString());return tn(async()=>{let a=o.int32();return s&&(a+=o.int32()),(await r.iterator()).shuffle(e,a.toString())},this.size)}take(e){const t=this;let s;return this.size!=null&&this.size>e?s=e:this.size!=null&&this.size<=e?s=this.size:s=null,tn(async()=>(await t.iterator()).take(e),s)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}Wo.MAX_BUFFER_SIZE=1e4;function tn(n,e=null){return new class extends Wo{constructor(){super(...arguments),this.size=e}async iterator(){return n()}}}function Jz(n){return tn(async()=>fv(n),n.length)}function Qz(n){if(!ko(n))throw new Error("The argument to zip() must be an object or array.");let e;if(Array.isArray(n))for(let t=0;t{const t=await dv(n,s=>{if(s instanceof Wo)return{value:s.iterator(),recurse:!1};if(ko(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return Mz(t,Gs.SHORTEST)},e)}function eM(n){if(n===null)return null;const e=n[0];return _z(e)?{value:tM(n),recurse:!1}:{value:null,recurse:!0}}function tM(n){if(n.length===0)throw new Error("Can't make a batch of zero elements.");return n[0]instanceof Re?Xt(n):xn(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class yv extends Wo{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(` +`).map(r=>(r.endsWith("\r")&&(r=r.slice(0,-1)),r))}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */const ul='"',sa=Symbol("out"),Ab=Symbol("field"),cl=Symbol("quote"),Ph=Symbol("quoteafterquote"),Rb=Symbol("quoteinquote");class bv extends Wo{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&I(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((r,o)=>(r[o]=r[o]+1||1,r),{}),s=Object.keys(t).filter(r=>t[r]>1);if(I(s.length===0,()=>"Duplicate column names found: "+s.toString()),this.columnConfigs){for(const r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");const s=t.value;return this.parseRow(s,!1)}else return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new yv(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(I(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),s={},r={};for(let o=0;o14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!B().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new Hg(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(s){throw new Error(`Error thrown while initializing video stream: ${s.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const s=await this.getAudioData();if(this.includeSpectrogram){const r=this.flattenQueue(s.freqDataQueue);e=this.getTensorFromAudioDataArray(r,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const r=this.flattenQueue(s.timeDataQueue);t=this.getTensorFromAudioDataArray(r,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let s=0;return new Promise(r=>{const o=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++s===this.numFrames&&(clearInterval(o),r({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,s=new Float32Array(e.length*t);return e.forEach((r,o)=>s.set(r,o*t)),s}getTensorFromAudioDataArray(e,t){const s=new Float32Array(G(t));return s.set(e,s.length-e.length),xn(s,t)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class jg extends vt{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Pt([0],"int32"),this.webcamConfig.centerCrop){const s=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,r=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,o=(1-s)/2,a=(1-r)/2,i=o+s,l=r+a;this.cropBox=Tr([a,o,l,i],[1,4])}else this.cropBox=Tr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!B().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const s=new jg(e,t);return await s.start(),s}async start(){this.webcamConfig.facingMode&&I(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=b0(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return z(()=>{const t=Lt(ee(e,"float32"),0);let s;s=Bn.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const r=s.shape;return F(s,r.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class xv{}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class wv extends vt{split(e){return new nM(this,e)}}class nM extends wv{constructor(e,t){super(),this.upstream=e,this.impl=new sM(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class sM extends Gg{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const s of t.slice(0,-1))this.outputQueue.push(s);return this.carryover=t[t.length-1],!0}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class rM extends vt{decodeUTF8(){return new oM(this)}}class oM extends wv{constructor(e){super(),this.upstream=e,this.impl=new aM(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class aM extends Gg{constructor(e){if(super(),this.upstream=e,B().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=require("string_decoder");this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t;if(e.done)return!1;t=e.value;let s;return B().get("IS_BROWSER")?s=this.decoder.decode(t,{stream:!0}):s=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(s),!0}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class vv extends rM{constructor(e,t={}){super(),this.file=e,this.options=t,I(e instanceof Uint8Array||(B().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,s)=>{const r=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,r)));else{const o=new FileReader;o.onload=i=>{let l=o.result;if(l instanceof ArrayBuffer&&(l=new Uint8Array(l)),!(l instanceof Uint8Array))return s(new TypeError("FileReader returned unknown type."));t(l)},o.onabort=i=>s(new Error("Aborted")),o.onerror=i=>s(new Error(i.type));const a=this.file.slice(this.offset,r);o.readAsArrayBuffer(a)}this.offset=r}),done:!1}}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */async function iM(n,e={},t){let s,r;typeof n=="string"?s=n:(s=n.url,r=lM(n));const o=await Nx(s,r);if(o.ok){const a=new Uint8Array(await o.arrayBuffer());return new vv(a,e)}else throw new Error(o.statusText)}const lM=n=>({method:n.method,headers:n.headers,body:n.body,mode:n.mode,credentials:n.credentials,cache:n.cache,redirect:n.redirect,referrer:n.referrer,integrity:n.integrity});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */function $v(n){return typeof n=="string"&&n.slice(0,7)==="file://"}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class Sv extends xv{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if($v(this.input)&&B().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.slice(7))}return new vv(this.input,this.options)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */class Iv extends xv{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return $v(this.url)?new Sv(this.url,this.fileOptions).iterator():iM(this.url,this.fileOptions)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */function uM(n,e={}){return new bv(new Iv(n),e)}function cM(n){const e=Ug(n);return tn(async()=>e)}function hM(n){return tn(async()=>{const e=await n();return Ug(()=>e.next())})}async function dM(n,e){return jg.create(n,e)}async function pM(n){return Hg.create(n)}/** @license See the LICENSE file. */const Nv="4.22.0";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const s9=Object.freeze(Object.defineProperty({__proto__:null,CSVDataset:bv,Dataset:Wo,FileDataSource:Sv,TextLineDataset:yv,URLDataSource:Iv,array:Jz,csv:uM,func:cM,generator:hM,microphone:pM,version_data:Nv,webcam:dM,zip:Qz},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function le(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&I(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fM=_c;class ph extends zd{nextDataId(){return ph.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new lx(this,Yn())}write(e,t,s){this.firstUse&&(this.firstUse=!1,B().get("IS_NODE")&&fn(` +============================ +Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. +============================`));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:s,refCount:1}),r}makeTensorInfo(e,t,s){let r;if(t==="string"&&s!=null&&s.length>0&&es(s[0])){const o=s.map(a=>ns(a));r=this.write(o,e,t)}else r=this.write(s,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,s,r,o){this.data.set(e,{values:t,dtype:r,refCount:o})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:s}=this.data.get(e);if(t==="complex64"){const r=this.readSync(s.real.dataId),o=this.readSync(s.imag.dataId);return ks(r,o)}return gx(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string")try{const s=t.map(r=>Ss(r));return ve(e.shape,e.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return ve(e.shape,e.dtype,t)}makeOutput(e,t,s){return Yn().makeTensorFromTensorInfo(this.makeTensorInfo(t,s,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:s}=this.data.get(e);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Nt();return e(),{kernelMs:Nt()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){le([e],"where");const t=this.readSync(e.dataId);return fM(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}ph.nextDataId=0;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cv(n){const e=new Float32Array(n.length);for(let t=0;t{const{x:e}=n.inputs,t=n.backend;le(e,"abs");let s=new Float32Array(G(e.shape));const r=t.data.get(e.dataId).values;return s=Cv(r),t.makeOutput(s,e.shape,e.dtype)},gM={kernelName:hu,backendName:"cpu",kernelFunc:mM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ot(n){return(e,t,s,r,o)=>{const a=ye(e,t),i=a.length,l=he(a),u=G(a),c=wt(o,u),h=e.length,d=t.length,p=he(e),f=he(t),g=Pr(e,a),m=Pr(t,a);if(g.length+m.length===0)for(let y=0;yw[E]=0);const x=Vn(w,h,p),$=b.slice(-d);m.forEach(E=>$[E]=0);const C=Vn($,d,f);c[y]=n(s[x],r[C])}return[c,a]}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sn(n){const{inputs:e,backend:t}=n,{real:s,imag:r}=e,o=t.data.get(s.dataId).values,a=t.data.get(r.dataId).values,i=t.makeTensorInfo(s.shape,"complex64"),l=t.data.get(i.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(s.shape,"float32",o),imag:t.makeTensorInfo(r.shape,"float32",a)},i}const yM={kernelName:Yd,backendName:"cpu",kernelFunc:sn};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tu(n,e,t="float32"){if(t==="complex64"){const r=tu(n,e,"float32"),o=tu(n,e,"float32");return sn({inputs:{real:r,imag:o},backend:n})}const s=Et(G(e),t);return n.makeTensorInfo(e,t,s)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cs(n){const{inputs:e,backend:t}=n,{x:s}=e;return t.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const bM={kernelName:Qa,backendName:"cpu",kernelFunc:cs};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Wr(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.data.get(s.dataId).complexTensorInfos.real,o=t.data.get(r.dataId).values;return t.makeTensorInfo(r.shape,r.dtype,o)}const xM={kernelName:Ep,backendName:"cpu",kernelFunc:Wr};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kv(n,e,t,s){if(s==="int32"){const r=Int32Array.from(n);return[e,"int32",r]}if(s==="bool"){const r=ir([0],t),[o,a]=ot((i,l)=>i!==l?1:0)(e,[],n,r,"bool");return[a,"bool",o]}throw new Error(`Error in Cast: failed to cast ${t} to ${s}`)}function ar(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dtype:o}=s;if(o==="complex64"){if(r.dtype==="complex64")return cs({inputs:{x:r},backend:t});const c=tu(t,r.shape,r.dtype),h=ar({inputs:{x:r},backend:t,attrs:{dtype:"float32"}}),d=sn({inputs:{real:h,imag:c},backend:t});return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(h),d}if(r.dtype==="complex64"){const c=Wr({inputs:{input:r},backend:t}),h=ar({inputs:{x:c},backend:t,attrs:{dtype:o}});return t.disposeIntermediateTensorInfo(c),h}if(!Vd(r.dtype,o)){const c=cs({inputs:{x:r},backend:t});return{dataId:c.dataId,shape:c.shape,dtype:o}}const a=t.data.get(r.dataId).values,[i,l,u]=kv(a,r.shape,r.dtype,o);return t.makeTensorInfo(i,l,u)}const wM={kernelName:Ba,backendName:"cpu",kernelFunc:ar};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gt(n,e,t,s){return t==null?({inputs:r,backend:o})=>{const{a,b:i}=r,l=o;le([a,i],n);const u=l.data.get(a.dataId).values,c=l.data.get(i.dataId).values,h=a.dtype==="string"?Ts(u):u,d=a.dtype==="string"?Ts(c):c,p=s||a.dtype,[f,g]=e(a.shape,i.shape,h,d,p);return l.makeTensorInfo(g,p,f)}:({inputs:r,backend:o})=>{const{a,b:i}=r,l=o;if(a.dtype==="complex64"||i.dtype==="complex64"){const u=ar({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),c=l.data.get(u.dataId),h=c.complexTensorInfos.real,d=c.complexTensorInfos.imag,p=l.data.get(h.dataId).values,f=l.data.get(d.dataId).values,g=ar({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),m=l.data.get(g.dataId),y=m.complexTensorInfos.real,b=m.complexTensorInfos.imag,w=l.data.get(y.dataId).values,x=l.data.get(b.dataId).values,[$,C,E]=t(a.shape,i.shape,p,f,w,x),A=l.makeTensorInfo(E,"float32",$),k=l.makeTensorInfo(E,"float32",C),T=sn({inputs:{real:A,imag:k},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(g),l.disposeIntermediateTensorInfo(A),l.disposeIntermediateTensorInfo(k),T}else{const u=l.data.get(a.dataId).values,c=l.data.get(i.dataId).values,h=s||a.dtype,[d,p]=e(a.shape,i.shape,u,c,h);return l.makeTensorInfo(p,h,d)}}}function qg(n){return(e,t,s,r,o,a)=>{const i=ye(e,t),l=G(i),u=i.length,c=he(i),h=wt("float32",l),d=wt("float32",l),p=Pr(e,i),f=Pr(t,i),g=ks(s,r),m=ks(o,a),y=e.length,b=he(e),w=t.length,x=he(t);if(p.length+f.length===0)for(let $=0;$E[_]=0);const A=Vn(E,y,b),k=C.slice(-w);f.forEach(_=>k[_]=0);const T=Vn(k,w,x),S=n(g[A*2],g[A*2+1],m[T*2],m[T*2+1]);h[$]=S.real,d[$]=S.imag}return[h,d,i]}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tv=ot(((n,e)=>n+e)),vM=qg(((n,e,t,s)=>({real:n+t,imag:e+s}))),To=gt(Ro,Tv,vM),$M={kernelName:Ro,backendName:"cpu",kernelFunc:To};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kg(n,e,t,s,r){const o=G(s),a=Et(r,t);for(let i=0;i=r||(o>0?a[l]+=e[i]:a[l]+=1)}return a}function Ev(n,e,t,s=!1){const r=n.shape[0],o=n.shape[1],a=ve([r,t],e.dtype);for(let i=0;i=t||(s?a.set(1,i,u):e.size>0?a.set(a.get(i,u)+e.get(i,l),i,u):a.set(a.get(i,u)+1,i,u))}return a}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Av=ot(((n,e)=>n&e)),SM=gt(xu,Av),IM={kernelName:xu,backendName:"cpu",kernelFunc:SM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ps(n){return(e,t,s)=>{const r=tt(t,e.length);for(let o=0;o{const{x:a}=s;le(a,n);const i=o,l=i.data.get(a.dataId).values;let u;if(a.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=Ts(l)}else u=l;const c=t||a.dtype,h=e(u,c,r);return i.makeTensorInfo(a.shape,c,h)}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Rv=ps(n=>Math.ceil(n)),NM=mr(Va,Rv),CM={kernelName:Va,backendName:"cpu",kernelFunc:NM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dv(n,e,t,s){const r=tt(t,G(e));if(s&&t!=="string"){let o=0;n.forEach(a=>{const i=G(a.shape);r.set(a.vals,o),o+=i})}else{let o=0;n.forEach(a=>{const i=t==="string"?Ts(a.vals):a.vals;let l=0;for(let u=0;un===e?1:0),_v=gt(Tu,Ov,null,"bool"),kM={kernelName:Tu,backendName:"cpu",kernelFunc:_v};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fv=ps(n=>Math.exp(n)),Lv=mr(Ka,Fv,"float32"),TM={kernelName:Ka,backendName:"cpu",kernelFunc:Lv};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pv=ps(n=>Math.expm1(n)),EM=mr(Xa,Pv),AM={kernelName:Xa,backendName:"cpu",kernelFunc:EM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zv=ps(n=>Math.floor(n)),RM=mr(Ya,zv),DM={kernelName:Ya,backendName:"cpu",kernelFunc:RM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mv=ot((n,e)=>Math.floor(n/e)),OM=gt(Za,Mv,null,"int32"),_M={kernelName:Za,backendName:"cpu",kernelFunc:OM};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bv(n,e,t,s,r,o,a,i,l){const u=ve([s,o],t);for(let c=0;c=l/o)throw new Error(`Invalid indices: ${h} does not index into ${i}`);for(let p=0;pn>e?1:0),FM=gt(Du,Wv,null,"bool"),LM={kernelName:Du,backendName:"cpu",kernelFunc:FM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Uv=ot((n,e)=>n>=e?1:0),PM=gt(Ja,Uv,null,"bool"),zM={kernelName:Ja,backendName:"cpu",kernelFunc:PM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Gv=ot((n,e)=>nn<=e?1:0),VM=gt(Fu,Hv,null,"bool"),WM={kernelName:Fu,backendName:"cpu",kernelFunc:VM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jv(n,e,t){const s=(e-n)/(t-1),r=Et(t,"float32");r[0]=n;for(let o=1;oMath.log(n)),UM=mr(si,qv),GM={kernelName:si,backendName:"cpu",kernelFunc:UM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kv(n,e,t,s){const r=wt(s,G(t));for(let o=0;oi)&&(i=u)}r[o]=i}return r}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xv=ot(((n,e)=>Math.max(n,e))),HM=gt(oi,Xv),jM={kernelName:oi,backendName:"cpu",kernelFunc:HM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yv=ot(((n,e)=>Math.min(n,e))),qM=gt(ai,Yv),KM={kernelName:ai,backendName:"cpu",kernelFunc:qM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xg=ot(((n,e)=>n*e)),XM=qg(((n,e,t,s)=>({real:n*t-e*s,imag:n*s+e*t}))),fh=gt(li,Xg,XM),YM={kernelName:li,backendName:"cpu",kernelFunc:fh};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zv(n,e,t){const s=As(-1,t);return Xg([],e,s,n,t)}function ZM(n){const{inputs:e,backend:t}=n,{x:s}=e;le(s,"neg");const r=t.data.get(s.dataId).values,[o,a]=Zv(r,s.shape,s.dtype);return t.makeTensorInfo(a,s.dtype,o)}const JM={kernelName:ju,backendName:"cpu",kernelFunc:ZM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jv=ot(((n,e)=>n!==e?1:0)),QM=gt(qu,Jv,null,"bool"),eB={kernelName:qu,backendName:"cpu",kernelFunc:QM};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yg(n,e,t,s,r){const o=e.length,a=G(e),i=he(e),l=he(r),u=wt(t,G(r));for(let c=0;ct.disposeIntermediateTensorInfo(b)),t.makeTensorInfo(y,m,f)}const sB={kernelName:Qu,backendName:"cpu",kernelFunc:nB};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rB(n,e,t){n.forEach((s,r)=>{if(s<0||s>=t){const o=Xr(r,e.length,he(e)).join(",");throw new Error(`indices[${o}] = ${s} is not in [0, ${t})`)}})}function oB(n,e){for(let t=0;tr)throw new Error("Ragged splits must not point past values");for(let o=1;os[o])throw new Error("Ragged splits must be sorted in ascending order")}}function aB(n,e,t,s){const r=[];let o=0;const a=e.length-1+t.length,i=new Array(a).fill(null).map(()=>[0]);oB(t,s);let l=1;for(let u=0;u=0){const g=i[f],m=g[g.length-1]-p[c];for(let y=c;yr[a]=o)}return e}function Db(n,e){const t=n.slice(0,e);for(;t.length1)throw new Error("starts must be a scalar or vector");if(r.length>1)throw new Error("limits must be a scalar or vector");if(a.length>1)throw new Error("deltas must be a scalar or vector");const i=e.length===0,l=r.length===0,u=a.length===0,c=[];i||c.push(e[0]),l||c.push(r[0]),u||c.push(a[0]);for(let m=1;m0&&by)x=0;else if(x=Math.ceil(Math.abs((b-y)/w)),x>Ob)throw new Error(`Requires ((limit - start) / delta) <= ${Ob}`);d[m+1]=d[m]+x}const p=d[h],f=tt(t,p);let g=0;for(let m=0;ms&&(s=o)}return s}static getMaxWidthValueRowID(e){const t=e.length;if(t===0)return 0;let s=0,r=e[0],o=0;for(let a=1;a"Final length of result must be equal to firstDimension."),o}calculateOutputIndexRowSplit(e,t,s,r){const o=e.length,a=[];for(let i=0;i0&&a.length!==e[o-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,s,r){const o=e.length,a=[];if(o===0)return[];let i=0,l=e[0];if(l>=t.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${t.length}`);let u=t[l];a.push(u);for(let c=1;c=0&&(++i,i=t.length)throw new Error(`Got nextValueRowId=${h} which is not less than ${t.length}`);u=t[h]}a.push(u)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,s,r){const o=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case Nn.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(o,t,s,r);case Nn.ROW_SPLITS:if(o.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${o.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(o,t,s,r);default:throw new Error(`Unsupported partition type: ${Nn[a]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case Nn.FIRST_DIM_SIZE:return e[0];case Nn.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Nn.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Nn[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const t=this.getFirstDimensionSize(),s=this.calculateOutputSize(t),r=new Array(this.raggedRank+1);r[r.length-1]=1;for(let l=r.length-2;l>=0;--l)r[l]=r[l+1]*s[l+1];const o=Fb(s,!1),a=tt(this.valuesDType,G(o));if(r[0]*s[0]>0){let l=this.calculateFirstParentOutputIndex(t,r[0],s[0]);for(let u=1;u<=this.raggedRank;++u)l=this.calculateOutputIndex(u-1,l,r[u],s[u]);this.setOutput(this.raggedRank,l,a,o)}return[o,a]}setOutput(e,t,s,r){if(s.length===0)return;const o=this.values,a=s;let i=r.slice();i=i.slice(e+1);const l=G(i),u=t.length;let c=this.defaultValue;if(c.length!==l&&c.length!==1){const f=this.defaultValueShape;z(()=>{const g=F(c,f);c=yo(g,i).dataSync()})}let h=0,d=0,p=0;for(let f=0;f<=u;++f){let g=f=u){const m=s.length;g=Math.floor(m/l)}if(g>p)if(this.defaultValue.length===1)a.subarray(p*l,g*l).fill(this.defaultValue[0]),p=g;else for(;g>p;){const m=a.slice(p*l);_b(m,c,l),++p}g<0?(h=f+1,d=p):(h=f,d=p,p=d+1)}}}function _b(n,e,t){for(let s=0;s= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}t.push(s)}return t}function n$(n,e,t,s,r,o,a,i,l,u){return new nu(n,e,t,s,r,o,a,i,l,u).compute()}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function s$(n,e,t,s){const r=n===e,o=n1;if(r||o||a)return Et(0,s);const i=Math.abs(Math.ceil((e-n)/t)),l=Et(i,s);e1/Math.sqrt(n)),cB=mr(fi,r$),hB={kernelName:fi,backendName:"cpu",kernelFunc:cB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cr(n,e,t,s,r,o,a,i,l,u){const c=[s/r,r],h=n.values,d=e.values;if(s===0)return ve(t,e.dtype);const p=l instanceof pt?l:ve(c,e.dtype);typeof l=="string"||typeof l=="number"?p.values.fill(l):typeof l=="boolean"&&p.values.fill(+l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${g} does not index into ${t}`);for(let y=0;y1/(1+Math.exp(-n))),o$=Fe(xi,n=>1/(1+Math.exp(-n))),pB={kernelName:xi,backendName:"cpu",kernelFunc:o$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a$(n,e,t,s,r){const o=Gf(s,e,t),a=G(t),i=he(s);if(o){const h=Hf(e,i);return r==="string"?n.slice(h,h+a):n.subarray(h,h+a)}const l=r==="string"?Ts(n):n,u=ve(s,r,l),c=ve(t,r);for(let h=0;hf+e[g]);c.set(u.get(...p),...d)}return r==="string"?Z0(c.values):c.values}function Ur(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:o,size:a}=s;le(r,"slice");const[i,l]=Uc(r,o,a);Wf(r,i,l);const u=t.data.get(r.dataId).values,c=a$(u,i,l,r.shape,r.dtype);return t.makeTensorInfo(l,r.dtype,c)}const fB={kernelName:oc,backendName:"cpu",kernelFunc:Ur};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function i$(n,e,t,s,r,o,a){const i=e[0],l=o[0],u=new Array(l),c=new Array(i),h=e[1];if(l===0){if(i!==0)throw new Error(z0(i));const m=tt(t,0),y=tt(r,0);return[m,[0,h],y,u,c]}let d=!0,p=0;const f=new Array(l).fill(0);for(let m=0;m=l)throw new Error(B0(m,y,l));++f[y],d=d&&y>=p,p=y}let g=!0;for(let m=0;m0&&(f[m]+=f[m-1])}if(g&&d){const m=n,y=s;for(let b=0;b0){p[d-1]=1;for(let m=d-2;m>=0;--m)p[m]=p[m+1]*s[m+1]}const f=[];if(i>0){f[i-1]=1;for(let m=i-2;m>=0;--m)f[m]=f[m+1]*l[m+1]}const g=tt(t,a*i);for(let m=0;m0?r[i-1]+1:0;if(h<0)throw new Error(ld());const d=e.slice();d[0]=h;const p=d.reduce((w,x)=>w*x,1),f=tt(t,p);if(i===0)return h>0&&f.fill(a),[f,d];if(h<=0)throw new Error(ld());let g=0,m=1,y=0,b=r[g];for(;;){let w=0;if(m=w)throw new Error(j0())}if(b<0||b>=h)throw new Error(q0(b,h));b>y&&f.fill(a,y*u,b*u);for(let x=g;x=l[0])throw new Error(K0(x,s[x],l[0]));for(let C=0;Ci)break}return yMath.sqrt(n)),gB=Fe(vi,n=>Math.sqrt(n)),yB={kernelName:vi,backendName:"cpu",kernelFunc:gB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const u$=ot(((n,e)=>{const t=n-e;return t*t})),bB=gt($i,u$),xB={kernelName:$i,backendName:"cpu",kernelFunc:bB};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const c$=ps((n,e)=>{const{pattern:t,replaceGlobal:s,rewrite:r}=e;return n.replace(new RegExp(t,s?"g":""),r)}),wB=mr(cc,c$),vB={kernelName:cc,backendName:"cpu",kernelFunc:wB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function h$(n,e,t,s){const r=ve(n,e.dtype);for(let o=0;o0?0:i-l);let p=0;p+=u*this.leftPad.length;for(let b=0;bb.forEach(w=>g[m++]=w);for(let b=0;b0){y(e[d+h-1]);for(let b=0;b0){let l=t[0];if(l!==0)throw new Error(`First split value must be 0, got ${l}`);for(let u=1;u=l;if(c=c&&t[u]<=s,!c)throw new Error(`Invalid split value ${t[u]}, must be in [${l}, ${s}]`);l=t[u]}if(l!==s)throw new Error(`Last split value must be data size. Expected ${s}, got ${l}`)}const o=r-1,a=tt("int32",r);if(s===0||r===0){const l=new Array(s);for(let u=0;u<=o;++u)a[u]=0;return[l,a]}a[0]=0;for(let l=1;l<=o;++l){const u=t[l]-t[l-1];let c=0;this.nGramWidths.forEach(h=>{c+=this.getNumNGrams(u,h)}),this.preserveShort&&u>0&&c===0&&(c=1),a[l]=a[l-1]+c}const i=new Array(a[o]);for(let l=0;l{const d=t[l+1]-t[l],p=this.getNumNGrams(d,h);this.createNGrams(e,u,i,c,p,h),c+=p}),this.preserveShort&&c===a[l]){const h=t[l+1]-t[l];if(h===0)continue;const d=h+2*this.padWidth;this.createNGrams(e,u,i,c,1,d)}}return[i,a]}}function d$(n,e,t,s,r,o,a,i){return new $B(t,s,r,o,a,i).compute(n,e)}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SB(n,e,t,s){if(!n.length)return;if(e.length===0){for(let o=0;on-e)),IB=qg(((n,e,t,s)=>({real:n-t,imag:e-s}))),Jg=gt(Si,m$,IB),NB={kernelName:Si,backendName:"cpu",kernelFunc:Jg};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function g$(n,e){const t=new Array(n.rank);for(let r=0;r{const t=e.value-n.value;return t===0?n.index-e.index:t};function y$(n,e,t=0,s=n.length-1){for(;s>t;){if(s-t>600){const i=s-t+1,l=e-t+1,u=Math.log(i),c=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*c*(i-c)/i)*Math.sign(l-i/2),d=Math.max(t,Math.floor(e-l*c/i+h)),p=Math.min(s,Math.floor(e+(i-l)*c/i+h));y$(n,e,d,p)}const r=n[e];let o=t,a=s;for(xs(n,t,e),ia(n[s],r)>0&&xs(n,t,s);o0;)a=a-1}ia(n[t],r)===0?xs(n,t,a):(a=a+1,xs(n,a,s)),a<=e&&(t=a+1),e<=a&&(s=a-1)}}function b$(n,e,t,s,r){const o=e[e.length-1],[a,i]=[n.length/o,o],l=wt(t,a*s),u=wt("int32",a*s);for(let h=0;hf[w]={value:b,index:w}),s{for(let m=0;mnew ph,1);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const w$=Fe(ja,n=>n>=0?n:Math.exp(n)-1),TB={kernelName:ja,backendName:"cpu",kernelFunc:w$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v$(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{alpha:o}=s;le([r],"leakyRelu");const a=G(r.shape),i=t.data.get(r.dataId).values,l=wt("float32",a);for(let u=0;un<0?e*n:n);function $$(n){const{inputs:e,backend:t}=n,{x:s,alpha:r}=e;le([s,r],"prelu");const o=t.data.get(s.dataId).values,a=t.data.get(r.dataId).values,[i,l]=AB(s.shape,r.shape,o,a,"float32");return t.makeTensorInfo(l,"float32",i)}const RB={kernelName:Ju,backendName:"cpu",kernelFunc:$$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const S$=Fe(hi,n=>Math.max(0,n)),DB={kernelName:hi,backendName:"cpu",kernelFunc:S$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const I$=Fe(di,n=>Math.min(Math.max(0,n),6)),OB={kernelName:di,backendName:"cpu",kernelFunc:I$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function su(n,e,t,s,r){if(t==="linear")return cs({inputs:{x:e},backend:n});if(t==="relu")return S$({inputs:{x:e},backend:n});if(t==="elu")return w$({inputs:{x:e},backend:n});if(t==="relu6")return I$({inputs:{x:e},backend:n});if(t==="prelu")return $$({inputs:{x:e,alpha:s},backend:n});if(t==="leakyrelu")return v$({inputs:{x:e},backend:n,attrs:{alpha:r}});if(t==="sigmoid")return o$({inputs:{x:e},backend:n});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ue(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{shape:o}=s,a=G(r.shape),i=Bd(o,a),l=G(i);I(a===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${r.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),t.incRef(r.dataId);const u=t.data.get(r.dataId);if(u.complexTensorInfos!=null){const c=u.complexTensorInfos.real,h=u.complexTensorInfos.imag;c.shape=i,h.shape=i}return{dataId:r.dataId,shape:i,dtype:r.dtype}}const _B={kernelName:ec,backendName:"cpu",kernelFunc:Ue};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N$(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:o}=e,{transposeA:a,transposeB:i}=s;le([r,o],"matMul");const l=r.shape.length,u=o.shape.length,c=a?r.shape[l-2]:r.shape[l-1],h=i?o.shape[u-1]:o.shape[u-2],d=a?r.shape[l-1]:r.shape[l-2],p=i?o.shape[u-2]:o.shape[u-1],f=r.shape.slice(0,-2),g=o.shape.slice(0,-2),m=G(f),y=G(g),w=ye(r.shape.slice(0,-2),o.shape.slice(0,-2)).concat([d,p]);I(c===h,()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${r.shape} and ${o.shape} and transposeA=${a} and transposeB=${i} must match.`);const x=a?[m,c,d]:[m,d,c],$=i?[y,p,h]:[y,h,p],C=Ue({inputs:{x:r},backend:t,attrs:{shape:x}}),E=Ue({inputs:{x:o},backend:t,attrs:{shape:$}}),A=a?C.shape[1]:C.shape[2],k=a?C.shape[2]:C.shape[1],T=i?E.shape[1]:E.shape[2],S=Math.max(m,y),_=t.data.get(C.dataId).values,P=t.data.get(E.dataId).values,V=he(C.shape),M=he(E.shape),[W,j,U]=a?[V[0],1,V[1]]:[V[0],V[1],1],[q,K,X]=i?[1,M[1],M[0]]:[M[1],1,M[0]],J=k*T,Q=ve([S,k,T],C.dtype),ne=Q.values,te=t.blockSize;for(let oe=0;oeMath.acos(n)),MB={kernelName:Oa,backendName:"cpu",kernelFunc:zB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BB=Fe(_a,n=>Math.acosh(n)),VB={kernelName:_a,backendName:"cpu",kernelFunc:BB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WB(n){const{inputs:e,backend:t}=n,s=e;le(e,"addN");const r=s.map(i=>t.data.get(i.dataId).values),o=ve(s[0].shape,s[0].dtype),a=o.values;for(let i=0;ib&&(b=$,w=x)}p[m]=w}return u.forEach(m=>t.disposeIntermediateTensorInfo(m)),t.makeTensorInfo(c,"int32",p)}const XB={kernelName:pu,backendName:"cpu",kernelFunc:KB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YB(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o}=s;le(r,"argMin");let a=Se(o,r.shape);const i=Je(a,r.shape.length);let l=r;const u=[];i!=null&&(l=Zt({inputs:{x:r},backend:t,attrs:{perm:i}}),u.push(l),a=st(a.length,l.shape.length)),a=[a[0]],Ot("argMin",a,l.shape.length);const[c,h]=St(l.shape,a),d=G(c),p=Et(d,"int32"),f=G(h),g=t.data.get(l.dataId).values;for(let m=0;mt.disposeIntermediateTensorInfo(m)),t.makeTensorInfo(c,"int32",p)}const ZB={kernelName:fu,backendName:"cpu",kernelFunc:YB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JB=Fe(Fa,n=>Math.asin(n)),QB={kernelName:Fa,backendName:"cpu",kernelFunc:JB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eV=Fe(La,n=>Math.asinh(n)),tV={kernelName:La,backendName:"cpu",kernelFunc:eV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nV=Fe(Pa,n=>Math.atan(n)),sV={kernelName:Pa,backendName:"cpu",kernelFunc:nV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rV=ot((n,e)=>Math.atan2(n,e)),oV=gt(Ma,rV),aV={kernelName:Ma,backendName:"cpu",kernelFunc:oV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iV=Fe(za,n=>Math.atanh(n)),lV={kernelName:za,backendName:"cpu",kernelFunc:iV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qg(n,e,t,s,r,o){const a=r.strideHeight,i=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,h=r.effectiveFilterWidth,d=r.padInfo.top,p=r.padInfo.left,f=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=ve(r.outShape,t),m=g.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],b=r.outShape[2]*r.outShape[3],w=r.outShape[3];for(let x=0;xj?j=te:o==="avg"&&(U+=te,q++)}if(isNaN(j))break}const K=_+P*w+E;m[K]=o==="avg"?U/q:j}}}return g}function C$(n,e,t,s,r=!1,o=!1){const a=ve(s.outShape,"int32"),i=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,h=s.effectiveFilterHeight,d=s.effectiveFilterWidth,p=s.padInfo.top,f=s.padInfo.left,g=ve(e,t,n);for(let m=0;mT&&(T=W,r?S=o?((m*s.inHeight+_)*s.inWidth+V)*s.inChannels+y:(_*s.inWidth+V)*s.inChannels+y:S=P*d+M)}}a.set(S,m,b,C,y)}}return a}function k$(n,e,t,s,r,o){const a=r.strideDepth,i=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,h=r.dilationWidth,d=r.effectiveFilterDepth,p=r.effectiveFilterHeight,f=r.effectiveFilterWidth,g=r.padInfo.front,m=r.padInfo.top,y=r.padInfo.left,b=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,w=ve(r.outShape,t),x=w.values,$=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[2]*r.outShape[3]*r.outShape[4],E=r.outShape[3]*r.outShape[4],A=r.outShape[4];for(let k=0;kme?me=He:o==="avg"&&(fe+=He,we++),isNaN(me))break}if(isNaN(me))break}if(isNaN(me))break}const $e=de+_;x[$e]=o==="avg"?fe/Math.max(we,1):me}}}}return w}function uV(n,e){const t=ve(e.outShape,"int32"),s=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,i=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=e.padInfo.front,p=e.padInfo.top,f=e.padInfo.left;for(let g=0;g=P&&(P=X,V=W*c*h+U*c+K)}}}t.set(V,g,y,$,k,m)}}}return t}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e;le(r,"avgPool");const{filterSize:o,strides:a,pad:i,dimRoundingMode:l}=s,u=1;I(Dt(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);const c=Dn(r.shape,o,a,u,i,l);let h;if(c.filterWidth===1&&c.filterHeight===1&&Ce(c.inShape,c.outShape))h=cs({inputs:{x:r},backend:t});else{const d=t.data.get(r.dataId).values,p=he(r.shape),f=Qg(d,r.shape,r.dtype,p,c,"avg");h=t.makeTensorInfo(c.outShape,r.dtype,f.values)}return h}const hV={kernelName:mu,backendName:"cpu",kernelFunc:cV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:o,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=s;le(r,"avgPool3d");const c=Rs(r.shape,o,a,1,i,l,u),h=t.data.get(r.dataId).values,d=k$(h,r.shape,r.dtype,he(r.shape),c,"avg");return t.makeTensorInfo(d.shape,"float32",d.values)}const pV={kernelName:gu,backendName:"cpu",kernelFunc:dV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fV(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=s;le([r,o],"avgPool3DGrad");const c=Rs(o.shape,a,i,1,l,u),h=c.strideDepth,d=c.strideHeight,p=c.strideWidth,f=c.filterDepth,g=c.filterHeight,m=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,w=c.dilationWidth,x=c.effectiveFilterDepth,$=c.effectiveFilterHeight,C=c.effectiveFilterWidth,E=x-1-c.padInfo.front,A=C-1-c.padInfo.left,k=$-1-c.padInfo.top,T=ve(o.shape,"float32"),S=1/(f*g*m),_=t.bufferSync(r);for(let P=0;P=c.outDepth||Math.floor(Q)!==Q))for(let ne=0;ne<$;ne+=b){const te=(q+ne)/d;if(!(te<0||te>=c.outHeight||Math.floor(te)!==te))for(let oe=0;oe=c.outWidth||Math.floor(de)!==de)continue;const me=_.get(P,Q,te,de,V);X+=me}}}T.set(X*S,P,M,W,j,V)}return t.makeTensorInfo(T.shape,T.dtype,T.values)}const mV={kernelName:qd,backendName:"cpu",kernelFunc:fV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gV(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o}=e,a=o;le([r,o],"avgPoolGrad");const{filterSize:i,strides:l,pad:u}=s,c=Dn(a.shape,i,l,1,u),h=c.strideHeight,d=c.strideWidth,p=c.filterHeight,f=c.filterWidth,g=c.dilationHeight,m=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,w=b-1-c.padInfo.left,x=y-1-c.padInfo.top,$=ve(a.shape,"float32"),C=1/(p*f),E=t.data.get(r.dataId).values,A=ve(r.shape,"float32",E);for(let k=0;k=c.outHeight||Math.floor(j)!==j))for(let U=0;U=c.outWidth||Math.floor(q)!==q)continue;const K=A.get(k,j,q,T);M+=K}}$.set(M*C,k,S,_,T)}return t.makeTensorInfo($.shape,$.dtype,$.values)}const yV={kernelName:jd,backendName:"cpu",kernelFunc:gV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,scale:o,offset:a,mean:i,variance:l}=e;I(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),I(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),I(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),le([r,i,l,o,a],"batchNorm");let{varianceEpsilon:u}=s;u==null&&(u=.001);const c=t.data.get(r.dataId).values,h=t.data.get(i.dataId).values,d=t.data.get(l.dataId).values,p=o?t.data.get(o.dataId).values:new Float32Array([1]),f=a?t.data.get(a.dataId).values:new Float32Array([0]),g=new Float32Array(c.length),m=f.length,y=p.length,b=d.length,w=h.length;let x=0,$=0,C=0,E=0;for(let A=0;A=m&&(x=0),$>=w&&($=0),C>=y&&(C=0),E>=b&&(E=0);return t.makeTensorInfo(r.shape,r.dtype,g)}const xV={kernelName:Au,backendName:"cpu",kernelFunc:bV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:o,crops:a}=s;le([r],"batchToSpaceND");const i=o.reduce((y,b)=>y*b),l=Pi(r.shape,o,i),u=zi(l.length,o.length),c=Mi(r.shape,o,i),h=Yf(a,o.length),d=Zf(c,a,o.length),p=Ue({inputs:{x:r},backend:t,attrs:{shape:l}}),f=Zt({inputs:{x:p},backend:t,attrs:{perm:u}}),g=Ue({inputs:{x:f},backend:t,attrs:{shape:c}}),m=Ur({inputs:{x:g},backend:t,attrs:{begin:h,size:d}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(g),m}const vV={kernelName:bu,backendName:"cpu",kernelFunc:wV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $V(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:o}=e,{size:a}=s,i=t.data.get(r.dataId).values,l=t.data.get(o.dataId).values,u=Kg(i,l,o.dtype,o.shape,a);return t.makeTensorInfo([a],o.dtype,u)}const SV={kernelName:Kd,backendName:"cpu",kernelFunc:$V};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IV(n){const{inputs:e,backend:t}=n,{s0:s,s1:r}=e,o=t.data.get(s.dataId).values,a=t.data.get(r.dataId).values,i=ye(Array.from(o),Array.from(a));return t.makeTensorInfo([i.length],"int32",Int32Array.from(i))}const NV={kernelName:Xd,backendName:"cpu",kernelFunc:IV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CV=Fe(Wa,(n,e)=>{const t=e;return n>t.clipValueMax?t.clipValueMax:n{const{x:e}=n.inputs,t=n.backend,s=new Float32Array(G(e.shape)),r=t.data.get(e.dataId),o=r.complexTensorInfos.real,a=r.complexTensorInfos.imag,i=t.data.get(o.dataId).values,l=t.data.get(a.dataId).values;for(let u=0;ug.shape);qf(a,o);let i=rs(e.map(g=>g.shape),o);if(G(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);const l=e.filter(g=>G(g.shape)>0);if(l.length===1)return cs({inputs:{x:l[0]},backend:t});if(l[0].dtype==="complex64"){const g=l.map(x=>Wr({inputs:{input:x},backend:t})),m=l.map(x=>Eo({inputs:{input:x},backend:t})),y=Ao({inputs:g,backend:t,attrs:{axis:o}}),b=Ao({inputs:m,backend:t,attrs:{axis:o}}),w=sn({inputs:{real:y,imag:b},backend:t});return g.forEach(x=>t.disposeIntermediateTensorInfo(x)),m.forEach(x=>t.disposeIntermediateTensorInfo(x)),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(b),w}const u=l.map(g=>{const y=[-1,G(g.shape.slice(o))];return Ue({inputs:{x:g},backend:t,attrs:{shape:y}})}),c=u.map(g=>({vals:t.data.get(g.dataId).values,shape:g.shape}));i=rs(u.map(g=>g.shape),1);const h=u[0].shape[0]===1,d=Dv(c,i,e[0].dtype,h),p=rs(l.map(g=>g.shape),o),f=t.makeTensorInfo(p,e[0].dtype,d);return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),f}const RV={kernelName:vu,backendName:"cpu",kernelFunc:Ao};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function T$(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:o}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=s;le([r,o],"conv2d");const h=Ds(l),d=$t(r.shape,o.shape,a,u,i,c,!1,h),p=d.filterHeight,f=d.filterWidth,g=d.dilationHeight,m=d.dilationWidth,y=d.padInfo.left,b=d.padInfo.top,w=d.dataFormat==="channelsLast",x=new pt(d.outShape,r.dtype),$=he(r.shape),C=he(o.shape),E=$[0],A=w?$[1]:$[2],k=w?$[2]:1,T=w?1:$[1],S=x.strides[0],_=w?x.strides[1]:x.strides[2],P=w?x.strides[2]:1,V=w?1:x.strides[1],M=t.data.get(r.dataId).values,W=t.data.get(o.dataId).values,j=x.values;for(let U=0;U=d.inHeight)continue;const oe=ne*C[0],de=q+te*A;for(let me=0;me=d.inWidth)continue;const Be=oe+$e*C[1],Qe=de+Oe*k;let Ve=Be;for(let Le=0;Le=u.inDepth)continue;const U=W*k[0],q=S+j*A[1];for(let K=0;K=u.inHeight)continue;const te=U+Q*k[1],oe=q+ne*A[2];for(let de=0;de=u.inWidth)continue;const Oe=te+we*k[2],Be=oe+$e*u.inChannels;let Qe=Oe;for(let Ve=0;VeMath.cos(n)),GV={kernelName:Ua,backendName:"cpu",kernelFunc:UV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HV=Fe(Ga,n=>Math.cosh(n)),jV={kernelName:Ga,backendName:"cpu",kernelFunc:HV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qV(n){const{inputs:e,backend:t,attrs:s}=n,{image:r,boxes:o,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=s,[c,h,d,p]=r.shape,f=o.shape[0],[g,m]=i,y=ve([f,g,m,p],"float32"),b=t.data.get(o.dataId).values,w=t.data.get(a.dataId).values,x=t.data.get(r.dataId).values,$=he(r.shape),C=he(y.shape);for(let E=0;E=c)continue;const V=g>1?(S-k)*(h-1)/(g-1):0,M=m>1?(_-T)*(d-1)/(m-1):0;for(let W=0;W1?k*(h-1)+W*V:.5*(k+S)*(h-1);if(j<0||j>h-1){for(let U=0;U1?T*(d-1)+X*M:.5*(T+_)*(d-1);if(J<0||J>d-1){for(let oe=0;oe1?T*(d-1)+U*M:.5*(T+_)*(d-1);if(q<0||q>d-1){for(let J=0;Jy+f-b-1:(y,b)=>y+b;for(let y=0;yy+f-b-1:(y,b)=>y+b;for(let y=0;y`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`);const i=r.shape[0],l=r.shape[1],u=r.shape[2],c=r.shape[3],h=l*o,d=u*o,p=c/(o*o),f=t.data.get(r.dataId).values,g=new Float32Array(i*h*d*p);let m=0;for(let y=0;y`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const p=$t(r.shape,o.shape,a,d,i,u,!0),{filterHeight:f,filterWidth:g,dilationHeight:m,dilationWidth:y,padInfo:b}=p,w=b.left,x=b.top,$=p.outChannels/p.inChannels,C=new pt(p.outShape,r.dtype),E=t.data.get(r.dataId).values,A=t.data.get(o.dataId).values,k=C.values;for(let T=0;T=p.inHeight)continue;const U=W*h[0],q=S+j*c[1];for(let K=0;K=p.inWidth)continue;const te=U+Q*h[1],oe=q+ne*p.inChannels;let de=X,me=te;for(let fe=0;fe{const{x:s,filter:r}=n,{strides:o,pad:a,dilations:i}=t,l=e,u=l.data.get(s.dataId).values,c=s.shape.length,h=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:p,inHeight:f,inWidth:g,inChannels:m,outHeight:y,outWidth:b,padInfo:w,strideHeight:x,strideWidth:$,filterHeight:C,filterWidth:E,dilationHeight:A,dilationWidth:k,outShape:T}=Ai(s.shape,r.shape,o,a,"NHWC",i),S=G(T),_=T.length,P=tt(s.dtype,S);for(let M=0;M=0&&ne=0&&oeX&&(X=fe)}}}const J=Vn([M,W,U,K],_,he(T));P[J]=X}}}return{dataId:l.write(ir(P,s.dtype),T,s.dtype),shape:T,dtype:s.dtype}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hW={kernelName:Wh,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:s,filter:r,dy:o}=n,{strides:a,pad:i,dilations:l}=t,u=e,c=bn(s.shape,u.data.get(s.dataId).values),h=bn(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:g,outHeight:m,outWidth:y,padInfo:b,strideHeight:w,strideWidth:x,filterHeight:$,filterWidth:C,dilationHeight:E,dilationWidth:A,outShape:k}=Ai(s.shape,r.shape,a,i,"NHWC",l);I(o.rank===k.length,()=>`Error in ${Wh}, dy must have the same rank as output ${k.length}, but got ${o.rank}`);const T=bn(k,u.data.get(o.dataId).values),S=Wd(r.shape,r.dtype);for(let P=0;P=0&&Q=0&&teq&&(q=oe,K=J,X=ne)}}}S[K][X][U]+=T[P][V][W][U]}}}return{dataId:u.write(ir(S,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dW={kernelName:Vh,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:s,filter:r,dy:o}=n,{strides:a,pad:i,dilations:l}=t,u=e,c=bn(s.shape,u.data.get(s.dataId).values),h=bn(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:g,outHeight:m,outWidth:y,padInfo:b,strideHeight:w,strideWidth:x,filterHeight:$,filterWidth:C,dilationHeight:E,dilationWidth:A,outShape:k}=Ai(s.shape,r.shape,a,i,"NHWC",l);I(o.rank===k.length,()=>`Error in ${Vh}, dy must have the same rank as output ${k.length}, but got ${o.rank}`);const T=bn(k,u.data.get(o.dataId).values),S=Wd(s.shape,s.dtype);for(let P=0;P=0&&Q=0&&teq&&(q=oe,K=Q,X=te)}}}S[P][K][X][U]+=T[P][V][W][U]}}}return{dataId:u.write(ir(S,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pW(n){const{inputs:e,backend:t,attrs:s}=n,{image:r}=e,{canvas:o,options:a}=s,{contextOptions:i,imageOptions:l}=a||{},u=(l==null?void 0:l.alpha)||1,c=(i==null?void 0:i.contextType)||"2d";if(c!=="2d")throw new Error(`Context type ${i.contextType} is not supported by the CPU backend.`);const h=o.getContext(c,(i==null?void 0:i.contextAttributes)||{});if(h==null)throw new Error(`Could not get the context with ${c} type.`);const[d,p]=r.shape.slice(0,2),f=r.shape.length===2?1:r.shape[2],g=t.data.get(r.dataId).values,m=r.dtype==="float32"?255:1,y=new Uint8ClampedArray(p*d*4);for(let w=0;w1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${E}.`)}else if(r.dtype==="int32"&&(E<0||E>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${E}.`);f===1?(x[0]=E*m,x[1]=E*m,x[2]=E*m):x[C]=E*m}const $=w*4;y[$+0]=Math.round(x[0]),y[$+1]=Math.round(x[1]),y[$+2]=Math.round(x[2]),y[$+3]=Math.round(x[3])}o.width=p,o.height=d;const b=new ImageData(y,p,d);return h.putImageData(b,0,0),r}const fW={kernelName:ip,backendName:"cpu",kernelFunc:pW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xi(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s;le(r,"sum");let i;r.dtype==="bool"?i=ar({inputs:{x:r},backend:t,attrs:{dtype:"int32"}}):i=cs({inputs:{x:r},backend:t});const l=i.shape.length,u=Se(o,i.shape),c=Je(u,l);let h=u,d=i;c!=null&&(d=Zt({inputs:{x:i},backend:t,attrs:{perm:c}}),h=st(h.length,l)),Ot("sum",h,d.shape.length);const[p,f]=St(d.shape,h),g=an(d.dtype,"int32");let m=tu(t,p,g);const y=G(f),b=t.data.get(m.dataId).values,w=t.data.get(d.dataId).values;for(let x=0;x=0&&(d=Xi({inputs:{x:d},backend:t,attrs:{axis:u[g]-(a.length-p),keepDims:!1}}),f.push(d)),p--)}for(const g of f)g!==d&&t.disposeIntermediateTensorInfo(g);return d}const yW={kernelName:lp,backendName:"cpu",kernelFunc:gW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bW(n){const{inputs:e,backend:t}=n,{dy:s,y:r}=e;le([s,r],"eluGrad");const o=new Float32Array(G(r.shape)),a=t.data.get(r.dataId).values,i=t.data.get(s.dataId).values;for(let l=0;l=0?o[l]=i[l]:o[l]=i[l]*(u+1)}return t.makeTensorInfo(r.shape,"float32",o)}const xW={kernelName:up,backendName:"cpu",kernelFunc:bW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wW=Jf,vW=Qf,$W=em,SW=tm,IW=nm,NW=sm,CW=Fe(qa,n=>{const e=Math.sign(n),t=Math.abs(n),s=1/(1+wW*t);return e*(1-((((NW*s+IW)*s+SW)*s+$W)*s+vW)*s*Math.exp(-t*t))}),kW={kernelName:qa,backendName:"cpu",kernelFunc:CW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ru(n){const{inputs:e,backend:t,attrs:s}=n,{input:r}=e,{dim:o}=s,a=r.shape.length,i=r.shape.slice();let l=o;return o<0&&(I(-(a+1)<=o,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+o+1),i.splice(l,0,1),Ue({inputs:{x:r},backend:t,attrs:{shape:i}})}const TW={kernelName:Eu,backendName:"cpu",kernelFunc:ru};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EW=ot((n,e)=>n/e),ey=gt(Ha,EW),Ed={kernelName:Ha,backendName:"cpu",kernelFunc:ey};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A$(n,e,t){const s=n.shape,r=s[0],o=s[1],a=t.data.get(n.dataId),i=a.complexTensorInfos.real,l=a.complexTensorInfos.imag,u=[r,o],c=G(u),h=wt("float32",c),d=wt("float32",c);for(let m=0;m{const{image:s}=n,r=t,o=wt(s.dtype,G(s.shape)),[a,i,l,u]=s.shape,c=r.data.get(s.dataId).values;for(let d=0;d=0&&w=0,()=>`GatherV2: the index value ${$} is not in [0, ${c-1}]`)}let h=i;i==null&&(h=0);const d=G(o.shape),p=hm(r,o,l,h),f=Ue({inputs:{x:r},backend:t,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),g=Ue({inputs:{x:o},backend:t,attrs:{shape:[p.batchSize,d/p.batchSize]}}),m=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],y=t.bufferSync(g),b=t.bufferSync(f),w=Vv(b,y,m);return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(g),t.makeTensorInfo(p.outputShape,w.dtype,w.values)}const HW={kernelName:Ru,backendName:"cpu",kernelFunc:GW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jW(n){const{inputs:e,backend:t}=n,{input:s}=e,r=G(s.shape),o=s.shape[s.shape.length-1],a=r/o,i=Ue({inputs:{x:s},backend:t,attrs:{shape:[a,o]}}),l=A$(i,!0,t),u=Ue({inputs:{x:l},backend:t,attrs:{shape:s.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}const qW={kernelName:fp,backendName:"cpu",kernelFunc:jW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KW=Fe(ei,n=>Number.isFinite(n)?1:0,"bool"),XW={kernelName:ei,backendName:"cpu",kernelFunc:KW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YW=Fe(ti,n=>Math.abs(n)===1/0?1:0,"bool"),ZW={kernelName:ti,backendName:"cpu",kernelFunc:YW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JW=Fe(ni,n=>Number.isNaN(n)?1:0,"bool"),QW={kernelName:ni,backendName:"cpu",kernelFunc:JW};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function e4(n){const{backend:e,attrs:t}=n,{start:s,stop:r,num:o}=t,a=jv(s,r,o);return e.makeTensorInfo([a.length],"float32",a)}const t4={kernelName:gp,backendName:"cpu",kernelFunc:e4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n4=Fe(ri,n=>Math.log1p(n)),s4={kernelName:ri,backendName:"cpu",kernelFunc:n4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const r4=ot((n,e)=>n&&e),o4=gt(Lu,r4,null,"bool"),a4={kernelName:Lu,backendName:"cpu",kernelFunc:o4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const i4=Fe(Pu,n=>n?0:1,"bool"),l4={kernelName:Pu,backendName:"cpu",kernelFunc:i4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const u4=ot((n,e)=>n||e),c4=gt(zu,u4,null,"bool"),h4={kernelName:zu,backendName:"cpu",kernelFunc:c4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d4(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{depthRadius:o,bias:a,alpha:i,beta:l}=s;le(r,"LRN");const u=r.shape[3],c=u-1,h=t.data.get(r.dataId).values,d=G(r.shape),p=new Float32Array(d);function f(g){const m=g%u;let y=g-m+Math.max(0,m-o);const b=g-m+Math.min(m+o,c);let w=0;for(;y<=b;y++){const x=h[y];w+=x*x}return w}for(let g=0;g`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);const c=Dn(r.shape,o,a,u,i,l);let h;if(c.filterWidth===1&&c.filterHeight===1&&Ce(c.inShape,c.outShape))h=cs({inputs:{x:r},backend:t});else{const d=t.data.get(r.dataId).values,p=he(r.shape),f=Qg(d,r.shape,r.dtype,p,c,"max");h=t.makeTensorInfo(c.outShape,r.dtype,f.values)}return h}const b4={kernelName:Vu,backendName:"cpu",kernelFunc:y4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function x4(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:o,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=s;le(r,"maxPool3d");const c=Rs(r.shape,o,a,1,i,l,u),h=t.data.get(r.dataId).values,d=k$(h,r.shape,r.dtype,he(r.shape),c,"max");return t.makeTensorInfo(d.shape,"float32",d.values)}const w4={kernelName:Wu,backendName:"cpu",kernelFunc:x4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v4(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=s;le([r,o],"maxPool3DGrad");const c=Rs(o.shape,a,i,1,l,u),h=t.bufferSync(o),d=uV(h,c),p=c.strideDepth,f=c.strideHeight,g=c.strideWidth,m=c.dilationDepth,y=c.dilationHeight,b=c.dilationWidth,w=c.effectiveFilterDepth,x=c.effectiveFilterHeight,$=c.effectiveFilterWidth,C=w-1-c.padInfo.front,E=$-1-c.padInfo.left,A=x-1-c.padInfo.top,k=ve(o.shape,"float32"),T=t.bufferSync(r);for(let S=0;S=c.outDepth||Math.floor(X)!==X))for(let J=0;J=c.outHeight||Math.floor(Q)!==Q))for(let ne=0;ne<$;ne+=b){const te=(U+ne)/g;if(te<0||te>=c.outWidth||Math.floor(te)!==te)continue;const oe=w*x*$-1-d.get(S,X,Q,te,_),de=K*x*$+J*$+ne,me=oe===de?1:0;if(me===0)continue;const fe=T.get(S,X,Q,te,_);q+=fe*me}}}k.set(q,S,P,V,M,_)}return t.makeTensorInfo(k.shape,k.dtype,k.values)}const $4={kernelName:xp,backendName:"cpu",kernelFunc:v4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function S4(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o,output:a}=e,i=o;le([o,a],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,d=Dn(i.shape,l,u,1,c,h),p=t.data.get(i.dataId).values,f=ve(d.outShape,i.dtype,C$(p,i.shape,i.dtype,d).values),g=d.strideHeight,m=d.strideWidth,y=d.dilationHeight,b=d.dilationWidth,w=d.effectiveFilterHeight,x=d.effectiveFilterWidth,$=x-1-d.padInfo.left,C=w-1-d.padInfo.top,E=ve(i.shape,"float32"),A=t.data.get(r.dataId).values,k=ve(r.shape,"float32",A);for(let T=0;T=d.outHeight||Math.floor(U)!==U))for(let q=0;q=d.outWidth||Math.floor(K)!==K)continue;const X=w*x-1-f.get(T,U,K,S),J=j*x+q,Q=X===J?1:0;if(Q===0)continue;const ne=k.get(T,U,K,S);W+=ne*Q}}E.set(W,T,_,P,S)}return t.makeTensorInfo(E.shape,E.dtype,E.values)}const I4={kernelName:bp,backendName:"cpu",kernelFunc:S4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N4(n,e,t,s,r){const o=he(e),a=Qg(n,e,t,o,r,"max"),i=C$(n,e,t,r,!0,s);return[a.values,i.values]}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const C4={kernelName:wp,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{filterSize:r,strides:o,pad:a,includeBatchInIndex:i}=e,l=t;le(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=Dn(s.shape,r,o,[1,1],a),[h,d]=N4(u,s.shape,s.dtype,i,c),p=l.write(h,c.outShape,s.dtype),f=l.write(d,c.outShape,s.dtype);return[{dataId:p,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function k4(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s,i=Se(o,r.shape),u=St(r.shape,i)[1],c=G(u),h=[],d=t.makeTensorInfo([],"float32",new Float32Array([c]));h.push(d);const p=ar({inputs:{x:r},backend:t,attrs:{dtype:"float32"}});h.push(p);const f=ey({inputs:{a:p,b:d},backend:t});h.push(f);const g=Xi({inputs:{x:f},backend:t,attrs:{axis:o,keepDims:a}});return h.forEach(m=>t.disposeIntermediateTensorInfo(m)),g}const T4={kernelName:Uu,backendName:"cpu",kernelFunc:k4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function E4(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s;le(r,"min");const i=Se(o,r.shape);let l=i;const u=Je(l,r.shape.length);let c=r;u!=null&&(c=Zt({inputs:{x:r},backend:t,attrs:{perm:u}}),l=st(l.length,r.shape.length)),Ot("min",l,c.shape.length);const[h,d]=St(c.shape,l),p=G(d),f=Et(G(h),c.dtype),g=t.data.get(c.dataId).values;for(let y=0;yw[0]+r.shape[x]+w[1]),l=o.map(w=>w[0]),u=o.map((w,x)=>w[0]+r.shape[x]),c=a==="reflect"?0:1,h=t.data.get(r.dataId).values,d=r.shape.length,p=he(r.shape),f=G(i),g=i.length,m=he(i),y=wt(r.dtype,f);for(let w=0;w=u[C]&&(x[C]=(u[C]-1)*2-x[C]+c);x=x.map((C,E)=>C-l[E]);const $=Vn(x,d,p);y[w]=h[$]}return{dataId:t.write(y,i,r.dtype),shape:i,dtype:r.dtype}}const D4={kernelName:Hu,backendName:"cpu",kernelFunc:R4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const O4=ot(((n,e)=>{const t=n%e;return n<0&&e<0||n>=0&&e>=0?t:(t+e)%e})),_4=gt(ii,O4),F4={kernelName:ii,backendName:"cpu",kernelFunc:_4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function D$(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{dim:o}=s,a=r.shape.length;let i=o;if(i===-1&&(i=a-1),i!==a-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${a} and dim was ${i}`);const l=Se([i],r.shape),u=R$({inputs:{x:r},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),c=nt(u.shape,l),h=Ue({inputs:{x:u},backend:t,attrs:{shape:c}}),d=Jg({inputs:{a:r,b:h},backend:t}),p=Lv({inputs:{x:d},backend:t}),f=Xi({inputs:{x:p},backend:t,attrs:{axis:l,keepDims:!1}}),g=Ue({inputs:{x:f},backend:t,attrs:{shape:c}}),m=ey({inputs:{a:p,b:g},backend:t});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(g),m}const L4={kernelName:uc,backendName:"cpu",kernelFunc:D$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function P4(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{numSamples:o,seed:a,normalized:i}=s;le(r,"multinomial");const l=i?r:D$({inputs:{logits:r},backend:t,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],h=t.data.get(l.dataId).values,d=[u,o],p=Et(G(d),"int32");for(let f=0;f=0&&h[d]{Rt(o,c.shape,"All tensors passed to stack must have matching shapes"),I(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const i=[],l=e.map(c=>{const h=ru({inputs:{input:c},backend:t,attrs:{dim:r}});return i.push(h),h}),u=Ao({inputs:l,backend:t,attrs:{axis:r}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}const J4={kernelName:Yu,backendName:"cpu",kernelFunc:_$};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Q4(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{paddings:o,constantValue:a}=s;le(r,"pad");const i=o.map((b,w)=>b[0]+r.shape[w]+b[1]),l=o.map(b=>b[0]),u=t.data.get(r.dataId).values,c=G(r.shape),h=r.shape.length,d=he(r.shape),p=G(i),f=i.length,g=he(i),m=wt(r.dtype,p);a!==0&&m.fill(a);for(let b=0;bC+l[E]),$=Vn(x,f,g);m[$]=u[b]}return{dataId:t.write(m,i,r.dtype),shape:i,dtype:r.dtype}}const F$={kernelName:Zu,backendName:"cpu",kernelFunc:Q4};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eU=ot((n,e)=>Math.pow(n,e)),tU=gt(ui,eU),nU={kernelName:ui,backendName:"cpu",kernelFunc:tU};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sU(n){const{inputs:e,backend:t,attrs:s}=n,{paramsNestedSplits:r,paramsDenseValues:o,indices:a}=e,{outputRaggedRank:i}=s,l=r.map(y=>t.data.get(y.dataId).values),u=r.map(y=>y.shape),c=t.data.get(o.dataId).values,h=t.data.get(a.dataId).values,[d,p,f]=e$(l,u,c,o.shape,o.dtype,h,a.shape),g=d.map(y=>t.makeTensorInfo([y.length],"int32",y)),m=t.makeTensorInfo(f,o.dtype,p);return g.concat([m])}const rU={kernelName:Np,backendName:"cpu",kernelFunc:sU};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oU(n){const{inputs:e,backend:t}=n,{starts:s,limits:r,deltas:o}=e,a=t.data.get(s.dataId).values,i=t.data.get(r.dataId).values,l=t.data.get(o.dataId).values,[u,c]=t$(a,s.shape,s.dtype,i,r.shape,l,o.shape),h=t.makeTensorInfo([u.length],"int32",u),d=t.makeTensorInfo([c.length],s.dtype,c);return[h,d]}const aU={kernelName:Cp,backendName:"cpu",kernelFunc:oU};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iU(n){const{inputs:e,backend:t,attrs:s}=n,{shape:r,values:o,defaultValue:a,rowPartitionTensors:i}=e,{rowPartitionTypes:l}=s,u=t.data.get(r.dataId).values,c=t.data.get(o.dataId).values,h=t.data.get(a.dataId).values,d=i.map(m=>t.data.get(m.dataId).values),p=i.map(m=>m.shape),[f,g]=n$(u,r.shape,c,o.shape,o.dtype,h,a.shape,d,p,l);return t.makeTensorInfo(f,o.dtype,g)}const lU={kernelName:kp,backendName:"cpu",kernelFunc:iU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uU(n){const{backend:e,attrs:t}=n,{start:s,stop:r,dtype:o,step:a}=t,i=s$(s,r,a,o);return e.makeTensorInfo([i.length],o,i)}const cU={kernelName:Tp,backendName:"cpu",kernelFunc:uU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hU=Fe(ci,n=>1/n),dU={kernelName:ci,backendName:"cpu",kernelFunc:hU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pU(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:o,halfPixelCenters:a,size:i}=s;le(r,"resizeBilinear");const l=he(r.shape),[u,c]=i,[h,d,p,f]=r.shape,g=t.data.get(r.dataId).values,m=new Float32Array(G([h,u,c,f])),y=[o&&u>1?d-1:d,o&&c>1?p-1:p],b=[o&&u>1?u-1:u,o&&c>1?c-1:c];let w=0;const x=y[0]/b[0],$=y[1]/b[1];for(let C=0;C1?u-1:u,a&&p>1?c-1:c],m=[a&&d>1?d-1:d,a&&p>1?p-1:p],y=g[0]/m[0],b=g[1]/m[1],w=t.data.get(o.dataId).values;let x=0;for(let $=0;$1?d-1:d,o&&c>1?p-1:p],b=[o&&u>1?u-1:u,o&&c>1?c-1:c],w=y[0]/b[0],x=y[1]/b[1];let $=0;for(let C=0;C1?c-1:c,a&&f>1?h-1:h],b=[a&&p>1?p-1:p,a&&f>1?f-1:f],w=y[0]/b[0],x=y[1]/b[1],$=1/w,C=1/x,E=Math.ceil($)*2+2,A=Math.ceil(C)*2+2;for(let k=0;k=p)continue;const Q=T+J*l[1],ne=J*w,te=Math.min(c-1,a?Math.round(ne):Math.floor(ne));if(S===te)for(let oe=0;oe=f)continue;const me=Q+de*l[2],fe=de*x,we=Math.min(h-1,a?Math.round(fe):Math.floor(fe));M===we&&(K+=m[me+q])}}g[W+q]=K}}}}return t.makeTensorInfo(r.shape,r.dtype,g)}const wU={kernelName:Ap,backendName:"cpu",kernelFunc:xU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vU(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dims:o}=s;le(r,"reverse");const a=r.shape.length,i=Se(o,r.shape);if(a===0)return cs({inputs:{x:r},backend:t});const l=new pt(r.shape,r.dtype),u=t.bufferSync(r);for(let c=0;cd[p]=r.shape[p]-1-d[p]),l.set(u.get(...d),...h)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}const $U={kernelName:sc,backendName:"cpu",kernelFunc:vU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SU={kernelName:Kp,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:s}=n,{radians:r,fillValue:o,center:a}=e,i=t,l=wt(s.dtype,G(s.shape)),[u,c,h,d]=s.shape,[p,f]=Xf(a,c,h),g=255,m=Math.sin(r),y=Math.cos(r),b=i.data.get(s.dataId).values;for(let x=0;x=0&&V=0&&M{const e=Math.floor(n);return n-e<.5?Math.floor(n):n-e>.5?Math.ceil(n):e%2===0?e:e+1}),NU={kernelName:pi,backendName:"cpu",kernelFunc:IU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function CU(n){const{inputs:e,backend:t,attrs:s}=n,{indices:r,updates:o}=e,{shape:a}=s,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=pr(o,r,a),d=!0,p=t.bufferSync(r),f=t.bufferSync(o),g=Cr(p,f,a,h,u,l,i,c,0,d);return t.makeTensorInfo(a,g.dtype,g.values)}const kU={kernelName:Dp,backendName:"cpu",kernelFunc:CU};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TU(n,e){let t=0,s=n.length,r=0;for(;t1||r.shape.length===1?1:G(r.shape.slice(1));for(let f=0;fn>=0?LU*n:FU*(Math.exp(n)-1)),zU={kernelName:mi,backendName:"cpu",kernelFunc:PU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MU=Fe(bi,n=>n<0?-1:n>0?1:0),BU={kernelName:bi,backendName:"cpu",kernelFunc:MU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VU=Fe(gi,n=>Math.sin(n)),WU={kernelName:gi,backendName:"cpu",kernelFunc:VU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UU=Fe(yi,n=>Math.sinh(n)),GU={kernelName:yi,backendName:"cpu",kernelFunc:UU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HU=11920928955078125e-23,Lb=Math.log(HU)+2,jU=Fe(wi,n=>{const e=n>-Lb,t=nNumber(m)))),t.makeTensorInfo([g.length],s.dtype,new Int32Array(g))]}const ZU={kernelName:Fp,backendName:"cpu",kernelFunc:YU};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JU(n){const{inputs:e,backend:t}=n,{inputIndices:s,inputShape:r,newShape:o}=e;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape + ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape + ${r.shape}`);if(o.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${o.shape}`);const a=Array.from(t.data.get(r.dataId).values),i=t.data.get(s.dataId).values,l=Array.from(t.data.get(o.dataId).values),[u,c,h]=l$(i,s.shape,s.dtype,a,l);return[t.makeTensorInfo(c,s.dtype,u),t.makeTensorInfo([h.length],o.dtype,new Int32Array(h))]}const QU={kernelName:Lp,backendName:"cpu",kernelFunc:JU};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eG(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:o}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(o.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${o.shape}`);if(r.shape[0]!==o.shape[0])throw new Error("segmentIds and indices should have same size.");const a=t.data.get(s.dataId).values,i=t.data.get(r.dataId).values,l=t.data.get(o.dataId).values,[u,c]=Zg(a,s.shape,s.dtype,i,l,!0);return t.makeTensorInfo(c,s.dtype,u)}const tG={kernelName:Pp,backendName:"cpu",kernelFunc:eG};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nG(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:o}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(o.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${o.shape}`);if(r.shape[0]!==o.shape[0])throw new Error("segmentIds and indices should have same size.");const a=t.data.get(s.dataId).values,i=t.data.get(r.dataId).values,l=t.data.get(o.dataId).values,[u,c]=Zg(a,s.shape,s.dtype,i,l);return t.makeTensorInfo(c,s.dtype,u)}const sG={kernelName:zp,backendName:"cpu",kernelFunc:nG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rG(n){const{inputs:e,backend:t,attrs:s}=n,{sparseIndices:r,sparseValues:o,defaultValue:a}=e,{outputShape:i}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:d}=pr(o,r,i),p=!1,f=t.bufferSync(r);let g;switch(o.dtype){case"bool":{const m=t.bufferSync(o),y=!!t.data.get(a.dataId).values[0];g=Cr(f,m,i,d,c,u,l,h,y,p);break}case"float32":{const m=t.bufferSync(o),y=t.data.get(a.dataId).values[0];g=Cr(f,m,i,d,c,u,l,h,y,p);break}case"int32":{const m=t.bufferSync(o),y=t.data.get(a.dataId).values[0];g=Cr(f,m,i,d,c,u,l,h,y,p);break}case"string":{const m=t.bufferSync(o),y=Ss(t.data.get(a.dataId).values[0]);g=Cr(f,m,i,d,c,u,l,h,y,p);break}default:throw new Error(`Unsupported type ${o.dtype}`)}return t.makeTensorInfo(i,g.dtype,g.values)}const oG={kernelName:Mp,backendName:"cpu",kernelFunc:rG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aG(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{numOrSizeSplits:o,axis:a}=s,i=Se(a,r.shape)[0],l=cm(r,o,i),u=new Array(r.shape.length).fill(0),c=r.shape.slice();return l.map(h=>{const d=[...c];d[i]=h;const p=Ur({inputs:{x:r},backend:t,attrs:{begin:u,size:d}});return u[i]+=h,p})}const iG={kernelName:lc,backendName:"cpu",kernelFunc:aG};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lG={kernelName:Bp,backendName:"cpu",kernelFunc:({inputs:n,backend:e})=>{const{x:t}=n,s=e;le(t,"square");const r=s.data.get(t.dataId).values,o=new Float32Array(r.length);for(let i=0;i{const t=e;return isNaN(n)?NaN:n>0?1:t.alpha}),cG={kernelName:ki,backendName:"cpu",kernelFunc:uG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hG(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:o,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=s;le(r,"stridedSlice");const{finalShapeSparse:p,finalShape:f,isIdentity:g,sliceDim0:m,isSimpleSlice:y,begin:b,end:w,strides:x}=jf(r.shape,o,a,i,l,u,c,h,d);let $;if(g)$=Ue({inputs:{x:r},backend:t,attrs:{shape:f}});else if(m||y){I(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const C=Uf(b,w,x),E=Ur({inputs:{x:r},backend:t,attrs:{begin:b,size:C}});$=Ue({inputs:{x:E},backend:t,attrs:{shape:f}}),t.disposeIntermediateTensorInfo(E)}else{const C=t.bufferSync(r),E=h$(p,C,x,b);$=t.makeTensorInfo(f,E.dtype,E.values)}return $}const dG={kernelName:Vp,backendName:"cpu",kernelFunc:hG};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pG(n){const{inputs:e,backend:t,attrs:s}=n,{separator:r,nGramWidths:o,leftPad:a,rightPad:i,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=e,d=t.data.get(c.dataId).values,p=t.data.get(h.dataId).values,[f,g]=d$(d,p,r,o,a,i,l,u);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(h.shape,"int32",g)]}const fG={kernelName:Wp,backendName:"cpu",kernelFunc:pG};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mG(n){const{inputs:e,backend:t,attrs:s}=n,{skipEmpty:r}=s,{input:o,delimiter:a}=e;if(o.dtype!=="string")throw new Error("Input must be of datatype string");if(o.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${o.shape}`);if(a.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);const i=t.data.get(o.dataId).values,l=t.data.get(a.dataId).values[0],[u,c,h]=p$(i,l,r),d=c.length;return[t.makeTensorInfo([d,2],"int32",u),t.makeTensorInfo([d],"string",c),t.makeTensorInfo([2],"int32",new Int32Array(h))]}const gG={kernelName:Up,backendName:"cpu",kernelFunc:mG};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yG(n){const{inputs:e,backend:t,attrs:s}=n,{numBuckets:r}=s,{input:o}=e;if(o.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const a=t.data.get(o.dataId).values,i=f$(a,r);return t.makeTensorInfo(o.shape,"int32",i)}const bG={kernelName:Gp,backendName:"cpu",kernelFunc:yG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xG=Fe(Ii,n=>Math.tan(n)),wG={kernelName:Ii,backendName:"cpu",kernelFunc:xG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vG=Fe(Ni,n=>Math.tanh(n)),$G={kernelName:Ni,backendName:"cpu",kernelFunc:vG};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SG(n){const{inputs:e,backend:t}=n,{tensor:s,indices:r,updates:o}=e,{sliceRank:a,numUpdates:i,sliceSize:l,strides:u,outputSize:c}=pr(o,r,s.shape),h=!1,d=t.bufferSync(r),p=t.bufferSync(o),f=t.bufferSync(s),g=Cr(d,p,s.shape,c,l,i,a,u,f,h);return t.makeTensorInfo(s.shape,g.dtype,g.values)}const IG={kernelName:Op,backendName:"cpu",kernelFunc:SG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NG(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{reps:o}=s;le(r,"tile");const a=g$(t.bufferSync(r),o);return t.makeTensorInfo(a.shape,a.dtype,a.values)}const CG={kernelName:Ci,backendName:"cpu",kernelFunc:NG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kG(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{k:o,sorted:a}=s;le(r,"topk");const i=t.data.get(r.dataId).values,[l,u]=b$(i,r.shape,r.dtype,o,a);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}const TG={kernelName:Hp,backendName:"cpu",kernelFunc:kG};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EG(n){const{inputs:e,attrs:t,backend:s}=n,{image:r,transforms:o}=e,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=t,[c,h,d,p]=r.shape,[f,g]=u??[h,d],m=[c,f,g,p],y=he(r.shape),b=y[0],w=y[1],x=y[2],$=he(m),C=$[0],E=$[1],A=$[2],k=wt(r.dtype,G(m));k.fill(l);const T=s.data.get(r.dataId).values,S=s.data.get(o.dataId).values;for(let P=0;Pe-1)if(e<=1)t=0;else{const s=2*e;t-=s*Math.trunc(t/s),t>=e&&(t=s-t-1)}return Ys(0,t,e-1)}function DG(n,e){let t=n;if(t<0)if(e<=1)t=0;else{const s=e-1;t+=e*(Math.trunc(-t/s)+1)}else if(t>e-1)if(e<=1)t=0;else{const s=e-1;t-=e*Math.trunc(t/s)}return Ys(0,t,e-1)}function OG(n,e){return n}function _G(n,e){return Ys(0,n,e-1)}function la(n,e,t,s,r,o,a,i,l,u,c){const h=a*s+i*r+l*o+u;return 0<=i&&it.disposeIntermediateTensorInfo(f)),p}const WG={kernelName:dc,backendName:"cpu",kernelFunc:VG};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UG=[PB,gM,MB,VB,$M,UB,HB,qB,XB,ZB,QB,tV,sV,aV,lV,hV,pV,mV,yV,FB,xV,vV,SV,IM,NV,wM,CM,kV,yM,EV,RV,DV,_V,LV,zV,BV,WV,GV,jV,KV,YV,JV,eW,nW,sW,oW,iW,uW,cW,hW,dW,fW,yW,TB,xW,kM,kW,TM,TW,AM,_W,FW,PW,DM,_M,MW,VW,UW,HW,LM,zM,bM,qW,AV,XW,ZW,QW,EB,BM,WM,t4,GM,s4,a4,l4,h4,p4,m4,g4,jM,b4,w4,$4,I4,C4,T4,A4,KM,D4,F4,z4,YM,JM,V4,G4,q4,eB,X4,Z4,J4,F$,nU,RB,sB,rU,aU,lU,cU,xM,Ed,dU,DB,OB,_B,fU,gU,bU,wU,$U,SU,NU,hB,kU,DU,_U,zU,pB,BU,WU,GU,fB,L4,qU,XU,ZU,QU,tG,sG,oG,iG,yB,lG,xB,vB,cG,dG,fG,gG,bG,NB,mW,wG,$G,IG,CG,TG,AG,tB,zG,BG,WG,Y4];for(const n of UG)Xp(n);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ir={},hl={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function GG(n,e){Ir[n]=e}function qn(n,e){if(!(n in Ir)||e!=null){const s=jG(n,e);if(s!==null)Ir[n]=s;else return console.log("Could not get context for WebGL version",n),null}const t=Ir[n];return t==null||t.isContextLost()?(delete Ir[n],qn(n)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),Ir[n])}function HG(n){if(!B().getBool("IS_SAFARI")&&typeof OffscreenCanvas<"u"&&n===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function jG(n,e){if(n!==1&&n!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=e??HG(n);return t.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete Ir[n]},!1),B().getBool("SOFTWARE_WEBGL_ENABLED")&&(hl.failIfMajorPerformanceCaveat=!1),n===1?t.getContext("webgl",hl)||t.getContext("experimental-webgl",hl):t.getContext("webgl2",hl)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Ta;(function(n){n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH"})(Ta||(Ta={}));var gn;(function(n){n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD"})(gn||(gn={}));var kt;(function(n){n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(kt||(kt={}));function Yi(n,e){return[e,n]}function qG(n,e){return n*e}function dl(n){const e=G(n),t=Math.ceil(e/4);return Rl(t)}function Uo(n,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(n/2))]}function KG(n,e){const[t,s]=Uo(n,e);return t*s*4}function ny(n,e){const t=n;let s,r,o,a,i,l,u,c,h,d;return B().getNumber("WEBGL_VERSION")===2?(s=t.R32F,r=t.R16F,o=t.RGBA16F,a=t.RGBA32F,i=t.RED,u=4,c=1,h=t.HALF_FLOAT,d=t.FLOAT,l=t.RGBA8):(s=n.RGBA,r=n.RGBA,o=n.RGBA,a=t.RGBA,i=n.RGBA,u=4,c=4,h=e!=null?e.HALF_FLOAT_OES:null,d=n.FLOAT,l=n.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:d}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function re(n,e){const t=e();return B().getBool("DEBUG")&&XG(n),t}function XG(n){const e=n.getError();if(e!==n.NO_ERROR)throw new Error("WebGL Error: "+P$(n,e))}const YG=596e-10,ZG=65504;function L$(n){return!!(B().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||n===0||YGn.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function z$(n,e){const t=Fs(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(re(n,()=>n.shaderSource(t,e)),re(n,()=>n.compileShader(t)),n.getShaderParameter(t,n.COMPILE_STATUS)===!1)throw console.log(n.getShaderInfoLog(t)),new Error("Failed to compile vertex shader.");return t}function M$(n,e){const t=Fs(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(re(n,()=>n.shaderSource(t,e)),re(n,()=>n.compileShader(t)),B().get("ENGINE_COMPILE_ONLY"))return t;if(n.getShaderParameter(t,n.COMPILE_STATUS)===!1)throw sy(e,n.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}const JG=/ERROR: [0-9]+:([0-9]+):/g;function sy(n,e){const t=JG.exec(e);if(t==null){console.log(`Couldn't parse line number in error: ${e}`),console.log(n);return}const s=+t[1],r=n.split(` +`),o=r.length.toString().length+2,a=r.map((h,d)=>kr((d+1).toString(),o)+h);let i=0;for(let h=0;hn.createProgram(),"Unable to create WebGLProgram.")}function V$(n,e){if(re(n,()=>n.linkProgram(e)),!B().get("ENGINE_COMPILE_ONLY")&&n.getProgramParameter(e,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function Cl(n,e){if(re(n,()=>n.validateProgram(e)),n.getProgramParameter(e,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function W$(n,e){const t=Fs(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return re(n,()=>n.bindBuffer(n.ARRAY_BUFFER,t)),re(n,()=>n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW)),t}function U$(n,e){const t=Fs(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return re(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t)),re(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,e,n.STATIC_DRAW)),t}function QG(){return B().getNumber("WEBGL_VERSION")===2?1:4}function G$(n){return Fs(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function H$(n,e){const t=B().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||e<=0){const s=`[${n}x${e}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(n>t||e>t){const s=`[${n}x${e}]`,r=`[${t}x${t}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+r+".")}}function j$(n){return Fs(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Rd(n,e,t,s,r,o,a){const i=n.getAttribLocation(e,t);return i===-1?!1:(re(n,()=>n.bindBuffer(n.ARRAY_BUFFER,s)),re(n,()=>n.vertexAttribPointer(i,r,n.FLOAT,!1,o,a)),re(n,()=>n.enableVertexAttribArray(i)),!0)}function q$(n,e,t){J$(n,t),re(n,()=>n.activeTexture(n.TEXTURE0+t)),re(n,()=>n.bindTexture(n.TEXTURE_2D,e))}function eH(n,e){J$(n,e),re(n,()=>n.activeTexture(n.TEXTURE0+e)),re(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function K$(n,e,t){return Fs(n,()=>n.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function X$(n,e,t){return n.getUniformLocation(e,t)}function Y$(n,e,t,s){re(n,()=>q$(n,e,s)),re(n,()=>n.uniform1i(t,s))}function tH(n){re(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,null)),re(n,()=>n.viewport(0,0,n.canvas.width,n.canvas.height)),re(n,()=>n.scissor(0,0,n.canvas.width,n.canvas.height))}function kl(n,e,t){re(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),re(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0))}function Dd(n,e){re(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),re(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function ca(n){const e=n.checkFramebufferStatus(n.FRAMEBUFFER);if(e!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Z$(n,e))}function Z$(n,e){switch(e){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${e}`}}function Fs(n,e,t){const s=re(n,()=>e());if(s==null)throw new Error(t);return s}function J$(n,e){const t=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=e+n.TEXTURE0;if(st){const r=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${r}.`)}}function Gr(n,e=2){return G(n.slice(0,n.length-e))}function Hr(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function ha(n){let e=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(e=[Gr(n),...Hr(n)]),e}function Q$(n,e=!1){let t=B().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=B().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");s===1/0&&B().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=t/2),e&&(t=t*2,s=s*2,n=n.map((i,l)=>l>=n.length-2?uu(n[l]):n[l]),n.length===1&&(n=[2,n[0]])),n.length!==2&&(n=Es(n).newShape);let r=G(n),o=null;n.length<=1&&r<=t?o=[1,r]:n.length===2&&n[0]<=t&&n[1]<=t?o=n:n.length===3&&n[0]*n[1]<=t&&n[2]<=t?o=[n[0]*n[1],n[2]]:n.length===3&&n[0]<=t&&n[1]*n[2]<=t?o=[n[0],n[1]*n[2]]:n.length===4&&n[0]*n[1]*n[2]<=t&&n[3]<=t?o=[n[0]*n[1]*n[2],n[3]]:n.length===4&&n[0]<=t&&n[1]*n[2]*n[3]<=t&&(o=[n[0],n[1]*n[2]*n[3]]);const a=o!=null&&Math.max(...o)>s&&Math.min(...o)<=(e?2:1)&&Math.min(...o)>0;if(o==null||a)if(e){const i=Gr(n);let l=2,u=2;n.length&&([l,u]=Hr(n)),r=i*(l/2)*(u/2),o=Rl(r).map(c=>c*2)}else o=Rl(r);return o}function pl(n){return n%2===0}function Ea(n,e){if(n=n.slice(-2),e=e.slice(-2),Ce(n,e)||!n.length||!e.length||n[0]===0||n[1]===0||e[0]===0||e[1]===0)return!0;if(n.length!==e.length){const t=n[n.length-1],s=e[e.length-1];if(t===s||pl(t)&&pl(s)&&(n[0]===1||e[0]===1))return!0}return n[1]===e[1]&&pl(n[0])&&pl(e[0])}let Tl,El;function eS(n){if(Tl==null){const e=qn(n);Tl=e.getParameter(e.MAX_TEXTURE_SIZE)}return Tl}function nH(){Tl=null}function sH(){El=null}function tS(n){if(El==null){const e=qn(n);El=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,El)}function nS(n){if(n===0)return 0;let e;const t=qn(n);return yn(t,"EXT_disjoint_timer_query_webgl2")&&n===2?e=2:yn(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function yn(n,e){return n.getExtension(e)!=null}function Od(n){try{if(qn(n)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function sS(n){if(n===0)return!1;const e=qn(n);if(n===1){if(!yn(e,"OES_texture_float"))return!1}else if(!yn(e,"EXT_color_buffer_float"))return!1;return _d(e)}function rS(n){if(n===0)return!1;const e=qn(n);if(n===1){if(!yn(e,"OES_texture_float")||!yn(e,"WEBGL_color_buffer_float"))return!1}else{if(yn(e,"EXT_color_buffer_float"))return _d(e);const s="EXT_color_buffer_half_float";if(yn(e,s)){const r=e.getExtension(s);return rH(e,r)}return!1}return _d(e)}function _d(n){const e=ny(n),t=n.createTexture();n.bindTexture(n.TEXTURE_2D,t),n.texImage2D(n.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);const o=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,o),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0);const a=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(t),n.deleteFramebuffer(o),a}function rH(n,e){const t=ny(n,e),s=n.createTexture();n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,t.internalFormatHalfFloat,1,1,0,t.textureFormatFloat,t.textureTypeHalfFloat,null);const a=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,s,0);const i=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(s),n.deleteFramebuffer(a),i}function oS(n){return n!==2?!1:qn(n).fenceSync!=null}function Go(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&I(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}const r9=Object.freeze(Object.defineProperty({__proto__:null,assertNotComplex:Go,bindCanvasToFramebuffer:tH,bindColorTextureToFramebuffer:kl,bindTextureToProgramUniformSampler:Y$,bindTextureUnit:q$,bindVertexBufferToProgramAttribute:Rd,callAndCheck:re,canBeRepresented:L$,createFragmentShader:M$,createFramebuffer:j$,createProgram:B$,createStaticIndexBuffer:U$,createStaticVertexBuffer:W$,createTexture:G$,createVertexShader:z$,getBatchDim:Gr,getExtensionOrThrow:ua,getFramebufferErrorMessage:Z$,getMaxTexturesInShader:tS,getNumChannels:QG,getProgramUniformLocation:X$,getProgramUniformLocationOrThrow:K$,getRowsCols:Hr,getShapeAs3D:ha,getTextureShapeFromLogicalShape:Q$,getWebGLDisjointQueryTimerVersion:nS,getWebGLErrorMessage:P$,getWebGLMaxTextureSize:eS,hasExtension:yn,isCapableOfRenderingToFloatTexture:sS,isDownloadFloatTextureEnabled:rS,isReshapeFree:Ea,isWebGLFenceEnabled:oS,isWebGLVersionEnabled:Od,linkProgram:V$,logShaderSourceAndInfoLog:sy,resetMaxTextureSize:nH,resetMaxTexturesInShader:sH,unbindColorTextureFromFramebuffer:Dd,unbindTextureUnit:eH,validateFramebuffer:ca,validateProgram:Cl,validateTextureSize:H$},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ue=B();ue.registerFlag("HAS_WEBGL",()=>ue.getNumber("WEBGL_VERSION")>0);ue.registerFlag("WEBGL_VERSION",()=>Od(2)?2:Od(1)?1:0);ue.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);ue.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>ue.get("WEBGL_VERSION")===2);ue.registerFlag("WEBGL_CPU_FORWARD",()=>!0);ue.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);ue.registerFlag("WEBGL_PACK",()=>ue.getBool("HAS_WEBGL"));ue.registerFlag("WEBGL_PACK_NORMALIZATION",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_CLIP",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_REDUCE",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_LAZILY_UNPACK",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_CONV_IM2COL",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>ue.getBool("WEBGL_PACK"));ue.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>eS(ue.getNumber("WEBGL_VERSION")));ue.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>tS(ue.getNumber("WEBGL_VERSION")));ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const n=ue.getNumber("WEBGL_VERSION");return n===0?0:nS(n)});ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>ue.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Jp());ue.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>sS(ue.getNumber("WEBGL_VERSION")));ue.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>ue.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:ue.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));ue.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>rS(ue.getNumber("WEBGL_VERSION")));ue.registerFlag("WEBGL_FENCE_API_ENABLED",()=>oS(ue.getNumber("WEBGL_VERSION")));ue.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>ue.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);ue.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)});ue.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Jp()?1:-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)});ue.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);ue.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);ue.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);ue.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);ue.registerFlag("WEBGL_EXP_CONV",()=>!1);ue.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>ue.getBool("IS_TEST"));ue.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);ue.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);ue.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);ue.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ht(){let n,e,t,s,r,o,a,i,l,u;return B().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",e="in",t="out",s="in",r="texture",o="outputColor",a="out vec4 outputColor;",i=B().getBool("WEBGL2_ISNAN_CUSTOM")?` + bool isnan_custom(float val) { + uint floatToUint = floatBitsToUint(val); + return (floatToUint & 0x7fffffffu) > 0x7f800000u; + } + + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan_custom(val.x), + isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); + } + + #define isnan(value) isnan_custom(value) + `:"",l="",u=` + #define round(value) newRound(value) + int newRound(float value) { + return int(floor(value + 0.5)); + } + + ivec4 newRound(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `):(n="",e="attribute",t="varying",s="varying",r="texture2D",o="gl_FragColor",a="",i=` + #define isnan(value) isnan_custom(value) + bool isnan_custom(float val) { + return (val > 0. || val < 1. || val == 0.) ? false : true; + } + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w)); + } + `,l=` + uniform float INFINITY; + + bool isinf(float val) { + return abs(val) == INFINITY; + } + bvec4 isinf(vec4 val) { + return equal(abs(val), vec4(INFINITY)); + } + `,u=` + int round(float value) { + return int(floor(value + 0.5)); + } + + ivec4 round(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `),{version:n,attribute:e,varyingVs:t,varyingFs:s,texture2D:r,output:o,defineOutput:a,defineSpecialNaN:i,defineSpecialInf:l,defineRound:u}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function so(n,e,t="index"){const s=he(e);return s.map((r,o)=>{const a=`int ${n[o]} = ${t} / ${r}`,i=o===s.length-1?`int ${n[o+1]} = ${t} - ${n[o]} * ${r}`:`index -= ${n[o]} * ${r}`;return`${a}; ${i};`}).join("")}function mh(n,e,t="index"){const s=he(e);return s.map((r,o)=>{const a=`int ${n[o]} = ${t} / outShapeStrides[${o}]`,i=o===s.length-1?`int ${n[o+1]} = ${t} - ${n[o]} * outShapeStrides[${o}]`:`index -= ${n[o]} * outShapeStrides[${o}]`;return`${a}; ${i};`}).join("")}function oH(n,e){const t=n.length,s=n.map(o=>`${e}[${o}]`),r=new Array(t-1);r[t-2]=s[t-1];for(let o=t-3;o>=0;--o)r[o]=`(${r[o+1]} * ${s[o+1]})`;return r}function aH(n,e,t="index"){const s=n.map((o,a)=>a),r=oH(s,e);return r.map((o,a)=>{const i=`int ${n[a]} = ${t} / ${r[a]}`,l=a===r.length-1?`int ${n[a+1]} = ${t} - ${n[a]} * ${r[a]}`:`index -= ${n[a]} * ${r[a]}`;return`${i}; ${l};`}).join("")}function ry(n){const e=he(n).map(t=>t.toString());return` + int getFlatIndex(ivec3 coords) { + return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z; + } +`}function oy(){return` + int getFlatIndex(ivec3 coords) { + return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z; + } +`}const aS=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + lowp vec4 encode_float(highp float v) { + if (isnan(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } +`;/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const{getBroadcastDims:iS}=tD;function iH(n,e,t){const s=[];if(n.forEach(p=>{const f=G(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?s.push(`uniform float ${p.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${p.name};`),s.push(`uniform int offset${p.name};`)),t.enableShapeUniforms){const{uniformShape:g}=ay(t.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(g.length){case 1:s.push(`uniform int ${p.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${p.name}Shape;`);break}s.push(`uniform ivec2 ${p.name}TexShape;`)}}),t.enableShapeUniforms){switch(e.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;");break}s.push("uniform ivec2 outTexShape;")}t.customUniforms&&t.customUniforms.forEach(p=>{s.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});const r=s.join(` +`),o=n.map(p=>lH(p,e,t.packedInputs,t.enableShapeUniforms)).join(` +`),a=e.texShape,i=Ht(),l=hH(i);let u,c,h=fH(i);return e.isPacked?(u=uH(e.logicalShape,a,t.enableShapeUniforms),c=pH(i)):(u=cH(e.logicalShape,a,t.enableShapeUniforms),c=dH(i)),t.packedInputs&&(h+=bH),[h,l,c,r,u,o,t.userCode].join(` +`)}function Ho(n,e=!1){const t=n.shapeInfo.logicalShape;switch(t.length){case 0:return AH(n,e);case 1:return DH(n,e);case 2:return _H(n,e);case 3:return LH(n,e);case 4:return zH(n,e);case 5:return MH(n);case 6:return BH(n);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function lS(n,e){switch(n.shapeInfo.logicalShape.length){case 0:return EH(n);case 1:return RH(n,e);case 2:return OH(n,e);case 3:return FH(n,e);default:return PH(n,e)}}function lH(n,e,t=!1,s){let r="";t?r+=lS(n,s):r+=Ho(n,s);const o=n.shapeInfo.logicalShape,a=e.logicalShape;return o.length<=a.length&&(t?r+=VH(n,e):r+=WH(n,e)),r}function uH(n,e,t){switch(n.length){case 0:return uS();case 1:return xH(n,e,t);case 2:return kH(n,e,t);case 3:return vH(n,e,t);default:return SH(n,e,t)}}function cH(n,e,t){switch(n.length){case 0:return uS();case 1:return wH(n,e,t);case 2:return TH(n,e,t);case 3:return $H(n,e,t);case 4:return IH(n,e,t);case 5:return NH(n,e);case 6:return CH(n,e);default:throw new Error(`${n.length}-D output sampling is not yet supported`)}}function hH(n){return` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${n.texture2D}(textureSampler, uv).r; + } + `}function dH(n){return` + void setOutput(float val) { + ${n.output} = vec4(val, 0, 0, 0); + } + `}function pH(n){return` + void setOutput(vec4 val) { + ${n.output} = val; + } + `}function fH(n){return`${n.version} + precision highp float; + precision highp int; + precision highp sampler2D; + ${n.varyingFs} vec2 resultUV; + ${n.defineOutput} + const vec2 halfCR = vec2(0.5, 0.5); + + struct ivec5 + { + int x; + int y; + int z; + int w; + int u; + }; + + struct ivec6 + { + int x; + int y; + int z; + int w; + int u; + int v; + }; + + uniform float NAN; + ${n.defineSpecialNaN} + ${n.defineSpecialInf} + ${n.defineRound} + + int imod(int x, int y) { + return x - y * (x / y); + } + + int idiv(int a, int b, float sign) { + int res = a / b; + int mod = imod(a, b); + if (sign < 0. && mod != 0) { + res -= 1; + } + return res; + } + + //Based on the work of Dave Hoskins + //https://www.shadertoy.com/view/4djSRW + #define HASHSCALE1 443.8975 + float random(float seed){ + vec2 p = resultUV * seed; + vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1); + p3 += dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + ${mH} + ${gH} + ${yH} + `}const mH=` +vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,gH=` +vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, + int texNumC, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,yH=` +vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,bH=` + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + float getChannel(vec4 frag, int dim) { + float modCoord = mod(float(dim), 2.); + return modCoord == 0. ? frag.r : frag.g; + } +`;function uS(){return` + int getOutputCoords() { + return 0; + } + `}function xH(n,e,t){const s=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return s[0]===1?t?` + int getOutputCoords() { + return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0)); + } + `:` + int getOutputCoords() { + return 2 * int(resultUV.x * ${s[1]}.0); + } + `:s[1]===1?t?` + int getOutputCoords() { + return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0)); + } + `:` + int getOutputCoords() { + return 2 * int(resultUV.y * ${s[0]}.0); + } + `:t?` + int getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y); + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${s[0]}, ${s[1]})); + return 2 * (resTexRC.x * ${s[1]} + resTexRC.y); + } + `}function wH(n,e,t){return e[0]===1?t?` + int getOutputCoords() { + return int(resultUV.x * float(outTexShape[1])); + } + `:` + int getOutputCoords() { + return int(resultUV.x * ${e[1]}.0); + } + `:e[1]===1?t?` + int getOutputCoords() { + return int(resultUV.y * float(outTexShape[0])); + } + `:` + int getOutputCoords() { + return int(resultUV.y * ${e[0]}.0); + } + `:t?` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(outTexShape[0], outTexShape[1])); + return resTexRC.x * outTexShape[1] + resTexRC.y; + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + return resTexRC.x * ${e[1]} + resTexRC.y; + } + `}function vH(n,e,t){if(t)return` + ivec3 getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0)); + int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + int index = resTexRC.x * packedTexShape[1] + resTexRC.y; + + int b = index / texelsInBatch; + index -= b * texelsInBatch; + + int r = 2 * (index / texelsInLogicalRow); + int c = imod(index, texelsInLogicalRow) * 2; + + return ivec3(b, r, c); + } + `;const s=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(n[2]/2),o=r*Math.ceil(n[1]/2);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${s[0]}, ${s[1]})); + int index = resTexRC.x * ${s[1]} + resTexRC.y; + + int b = index / ${o}; + index -= b * ${o}; + + int r = 2 * (index / ${r}); + int c = imod(index, ${r}) * 2; + + return ivec3(b, r, c); + } + `}function $H(n,e,t){if(t)return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(outTexShape[0], outTexShape[1])); + int index = resTexRC.x * outTexShape[1] + resTexRC.y; + ${mh(["r","c","d"],n)} + return ivec3(r, c, d); + } +`;const s=so(["r","c","d"],n);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.x * ${e[1]} + resTexRC.y; + ${s} + return ivec3(r, c, d); + } + `}function SH(n,e,t){if(t)return` + ivec4 getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + int index = resTexRC.x * packedTexShape[1] + resTexRC.y; + + int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0)); + int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0)); + int texelsInBatchN = texelsInBatch * outShape[1]; + + int b2 = index / texelsInBatchN; + index -= b2 * texelsInBatchN; + + int b = index / texelsInBatch; + index -= b * texelsInBatch; + + int r = 2 * (index / texelsInLogicalRow); + int c = imod(index, texelsInLogicalRow) * 2; + + return ivec4(b2, b, r, c); + } + `;const s=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(n[n.length-1]/2),o=r*Math.ceil(n[n.length-2]/2);let a=o,i="",l="b, r, c";for(let u=2;u=1?c="coords = 0;":c=i.map(b=>`coords.${h[b+u]} = 0;`).join(` +`);let d="";a<2&&o>0?d="coords":d=n.shapeInfo.logicalShape.map((b,w)=>`coords.${h[w+u]}`).join(", ");let p="return outputValue;";const g=G(n.shapeInfo.logicalShape)===1,y=G(e.logicalShape)===1;if(o===1&&!g&&!y)p=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(g&&!y)a===1?p=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:p=` + return vec4(outputValue.x); + `;else if(i.length){const b=o-2,w=o-1;i.indexOf(b)>-1&&i.indexOf(w)>-1?p="return vec4(outputValue.x);":i.indexOf(b)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(w)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return` + vec4 ${r}() { + ${l} coords = getOutputCoords(); + ${c} + vec4 outputValue = get${s}(${d}); + ${p} + } + `}function WH(n,e){const t=n.name,s=t.charAt(0).toUpperCase()+t.slice(1),r="get"+s+"AtOutCoords",o=e.texShape,a=n.shapeInfo.texShape,i=n.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!n.shapeInfo.isUniform&&i===l&&n.shapeInfo.flatOffset==null&&Ce(a,o))return` + float ${r}() { + return sampleTexture(${t}, resultUV); + } + `;const u=Pe(l),c=iS(n.shapeInfo.logicalShape,e.logicalShape),h=l-i;let d;const p=["x","y","z","w","u","v"];i===0?d="":l<2&&c.length>=1?d="coords = 0;":d=c.map(g=>`coords.${p[g+h]} = 0;`).join(` +`);let f="";return l<2&&i>0?f="coords":f=n.shapeInfo.logicalShape.map((g,m)=>`coords.${p[m+h]}`).join(", "),` + float ${r}() { + ${u} coords = getOutputCoords(); + ${d} + return get${s}(${f}); + } + `}function Pe(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function ay(n,e,t){const{newShape:s,keptDims:r}=Es(e),o=e.length,a=n&&o===3&&e[0]===1,i=a?e.slice(1):s,l=!n&&o>1&&!Ce(e,t)&&s.lengthn[t]).join(", ")}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UH(n,e,t,s){const r=t.map((c,h)=>{const d={logicalShape:c.shape,texShape:c.isUniform?null:c.texData.texShape,isUniform:c.isUniform,isPacked:c.isUniform?!1:c.texData.isPacked,flatOffset:null};return c.texData!=null&&c.texData.slice!=null&&c.texData.slice.flatOffset>0&&(d.flatOffset=c.texData.slice.flatOffset),{name:e.variableNames[h],shapeInfo:d}}),o=r.map(c=>c.shapeInfo),a={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},i=iH(r,a,e),l=M$(n.gl,i),u=n.createProgram(l);return B().get("ENGINE_COMPILE_ONLY")?{program:e,fragmentShader:l,source:i,webGLProgram:u,inShapeInfos:o,outShapeInfo:a,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(n.buildVao(u),Object.assign({program:e,fragmentShader:l,source:i,webGLProgram:u,inShapeInfos:o,outShapeInfo:a},cS(n,e,u)))}function cS(n,e,t){const s=[],r=[];let o,a,i,l=null,u=null;u=n.getUniformLocation(t,"NAN",!1),B().getNumber("WEBGL_VERSION")===1&&(l=n.getUniformLocation(t,"INFINITY",!1));const c=!1;for(const h of e.variableNames){const d={name:h,uniform:n.getUniformLocation(t,h,c),offset:n.getUniformLocation(t,`offset${h}`,c)};e.enableShapeUniforms&&(d.shape=n.getUniformLocation(t,`${h}Shape`,c),d.texShape=n.getUniformLocation(t,`${h}TexShape`,c)),s.push(d)}if(e.enableShapeUniforms&&(o=n.getUniformLocation(t,"outShape",c),i=n.getUniformLocation(t,"outShapeStrides",c),a=n.getUniformLocation(t,"outTexShape",c)),e.customUniforms)for(const h of e.customUniforms)r.push(n.getUniformLocation(t,h.name,c));return{variablesLocations:s,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:o,outShapeStridesLocation:i,outTexShapeLocation:a}}function zb(n,e){if(n.length!==e.length)throw Error(`Binary was compiled with ${n.length} inputs, but was executed with ${e.length} inputs`);n.forEach((t,s)=>{const r=t.logicalShape,o=e[s],a=o.shape;if(!Ce(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${a} must match`);if(t.isUniform&&o.isUniform)return;const i=t.texShape,l=o.isUniform?null:o.texData.texShape;if(!Ce(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function GH(n,e,t,s,r){e.program.enableShapeUniforms||(zb(e.inShapeInfos,t),zb([e.outShapeInfo],[s]));const o=s.texData.texture,a=s.texData.texShape;s.texData.isPacked?n.setOutputPackedMatrixTexture(o.texture,a[0],a[1]):n.setOutputMatrixTexture(o.texture,a[0],a[1]),n.setProgram(e.webGLProgram),n.bindVertexArray(e.webGLProgram.vao),B().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&n.gl.uniform1f(e.infLoc,1/0),e.nanLoc!==null&&n.gl.uniform1f(e.nanLoc,NaN);for(let l=0;l{const i=a.texData!=null&&a.texData.slice!=null&&a.texData.slice.flatOffset>0;if(n.enableShapeUniforms&&!a.isUniform){const l=a.texData.texShape,{useSqueezeShape:u,uniformShape:c,keptDims:h}=ay(n.packedInputs,a.shape,l);let d="",p="",f="";if(c.length===1&&n.packedInputs){const $=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];d=`${$[0]>1}_${$[1]>1}`}else if(c.length===2&&!n.packedInputs)p=`${c[0]>1}_${c[1]>1}`;else if(c.length>2&&!n.packedInputs){const $=he(c);f=`${$[0]===l[1]}_${$[$.length-1]===l[1]}`}const g=a.shape.length,m=c.length===2&&Ce(a.shape,l),y=G(a.shape)===1,b=Pr(a.shape,t.shape),w=!n.packedInputs&&g===t.shape.length&&Ce(l,t.texData.texShape),x=n.packedInputs||c.length>2?"":`${l[0]>1}_${l[1]>1}`;s+=`${g}_${w}_${u?h:""}_${c.length}_${y}_${b}_${m}_${d}_${p}_${f}_${x}_${i}`}else{const l=a.isUniform?"uniform":a.texData.texShape;s+=`${a.shape}_${l}_${i}`}});const r=n.userCode;let o=n.constructor.name;return o+="_"+s+"_"+r+`${B().getNumber("WEBGL_VERSION")}`,o}function Mt(n){return B().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&n<=4}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jH{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ta.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Ht();this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length),this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${this.enableShapeUniforms?mh(["r","c","d"],e):so(["r","c","d"],e)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); + int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getA(rc.x, rc.y, rc.z); + } + + ${t.output} = result; + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qH{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ta.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Ht();this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length),this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${this.enableShapeUniforms?mh(["r","c","d"],e):so(["r","c","d"],e)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); + int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z)); + } + + ${t.output} = result; + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class KH{constructor(e){this.variableNames=["A"],this.outTexUsage=gn.DOWNLOAD;const t=Ht();this.outputShape=e,this.userCode=` + ${aS} + + void main() { + float x = getAAtOutCoords(); + ${t.output} = encode_float(x); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class XH{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=gn.DOWNLOAD;const t=Ht();this.outputShape=e,this.userCode=` + ${aS} + + void main() { + ivec3 coords = getOutputCoords(); + float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); + ${t.output} = encode_float(x); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YH={R:0,G:1,B:2,A:3};class Mb{constructor(e,t=!1,s="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Ht();this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length);let o="result";t&&(o="floor(result * 255. + 0.5)");let a="";for(let i=0;in.bindTexture(i,a)),re(n,()=>n.texParameteri(i,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),re(n,()=>n.texParameteri(i,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),re(n,()=>n.texParameteri(i,n.TEXTURE_MIN_FILTER,n.NEAREST)),re(n,()=>n.texParameteri(i,n.TEXTURE_MAG_FILTER,n.NEAREST)),B().getNumber("WEBGL_VERSION")===1?re(n,()=>n.texImage2D(i,0,s,e,t,0,r,o,null)):re(n,()=>n.texStorage2D(i,1,s,e,t)),re(n,()=>n.bindTexture(n.TEXTURE_2D,null)),{texture:a,texShape:[t,e]}}function iy(n){return n.internalFormatFloat}function fS(n,e,t,s){const[r,o]=Yi(e,t);return Zi(n,r,o,iy(s),s.textureFormatFloat,n.FLOAT)}function ly(n){return n.internalFormatHalfFloat}function mS(n,e,t,s){const[r,o]=Yi(e,t);return Zi(n,r,o,ly(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function uy(n){return n.downloadTextureFormat}function gS(n,e,t,s){const[r,o]=Yi(e,t);return Zi(n,r,o,uy(s),n.RGBA,n.UNSIGNED_BYTE)}function cy(n){return n.internalFormatPackedFloat}function yS(n,e,t,s){const[r,o]=Uo(e,t);return Zi(n,r,o,cy(s),n.RGBA,n.FLOAT)}function hy(n){return n.internalFormatPackedHalfFloat}function bS(n,e,t,s){const[r,o]=Uo(e,t);return Zi(n,r,o,hy(s),n.RGBA,s.textureTypeHalfFloat)}function xS(n,e,t){return re(n,()=>n.bindBuffer(n.ARRAY_BUFFER,t)),Rd(n,e,"clipSpacePos",t,3,20,0)&&Rd(n,e,"uv",t,2,20,12)}function wS(n,e,t,s,r,o){re(n,()=>n.bindTexture(n.TEXTURE_2D,e));let a,i,l;r instanceof Uint8Array?(a=new Uint8Array(t*s*4),i=n.UNSIGNED_BYTE,l=n.RGBA):(a=new Float32Array(t*s*4),i=n.FLOAT,l=o.internalFormatPackedFloat),a.set(r),B().getNumber("WEBGL_VERSION")===2?re(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,t,s,n.RGBA,i,a)):re(n,()=>n.texImage2D(n.TEXTURE_2D,0,l,t,s,0,n.RGBA,i,a)),re(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function vS(n,e,t){re(n,()=>n.bindTexture(n.TEXTURE_2D,e)),t.data instanceof Uint8Array?B().getNumber("WEBGL_VERSION")===2?re(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,t.width,t.height,n.RGBA,n.UNSIGNED_BYTE,t.data)):re(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t.width,t.height,0,n.RGBA,n.UNSIGNED_BYTE,t.data)):B().getNumber("WEBGL_VERSION")===2?re(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,t)):re(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t)),re(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function $S(n,e,t,s){const r=n.createBuffer();re(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,r));const i=4*4*e*t;return re(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,i,n.STREAM_READ)),re(n,()=>n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,0)),re(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),r}function SS(n,e,t){const s=n,r=new Float32Array(t);return s.bindBuffer(s.PIXEL_PACK_BUFFER,e),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}function IS(n,e,t,s){const[r,o]=Yi(e,t),a=4,i=new Uint8Array(qG(e*t,a));return re(n,()=>n.readPixels(0,0,r,o,s.downloadTextureFormat,n.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function NS(n,e,t,s,r,o,a,i){const l=n,u=new Float32Array(KG(o,a));return l.bindBuffer(l.PIXEL_PACK_BUFFER,e),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function CS(n,e,t){const s=new Float32Array(e*t*4);return re(n,()=>n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,s)),s}const o9=Object.freeze(Object.defineProperty({__proto__:null,bindVertexProgramAttributeStreams:xS,createBufferFromOutputTexture:$S,createFloat16MatrixTexture:mS,createFloat16PackedMatrixTexture:bS,createFloat32MatrixTexture:fS,createIndexBuffer:pS,createPackedMatrixTexture:yS,createUnsignedBytesMatrixTexture:gS,createVertexBuffer:dS,createVertexShader:hS,downloadByteEncodedFloatMatrixFromOutputTexture:IS,downloadFloat32MatrixFromBuffer:SS,downloadMatrixFromPackedOutputTexture:CS,downloadPackedMatrixFromBuffer:NS,getInternalFormatForFloat16MatrixTexture:ly,getInternalFormatForFloat16PackedMatrixTexture:hy,getInternalFormatForFloat32MatrixTexture:iy,getInternalFormatForPackedMatrixTexture:cy,getInternalFormatForUnsignedBytesMatrixTexture:uy,uploadDenseMatrixToTexture:wS,uploadPixelDataToTexture:vS},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class zh{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=B().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,GG(t,e)):this.gl=qn(t),e=this.gl,B().getNumber("WEBGL_VERSION")===2){const o=e;this.createVertexArray=()=>re(o,()=>o.createVertexArray()),this.bindVertexArray=a=>re(o,()=>o.bindVertexArray(a)),this.deleteVertexArray=a=>re(o,()=>o.deleteVertexArray(a)),this.getVertexArray=()=>re(o,()=>o.getParameter(o.VERTEX_ARRAY_BINDING))}else if(e!=null){const o=e.getExtension("OES_vertex_array_object");if(o==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>re(e,()=>o.createVertexArrayOES()),this.bindVertexArray=a=>re(e,()=>o.bindVertexArrayOES(a)),this.deleteVertexArray=a=>re(e,()=>o.deleteVertexArrayOES(a)),this.getVertexArray=()=>re(e,()=>e.getParameter(o.VERTEX_ARRAY_BINDING_OES))}let s="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),B().getNumber("WEBGL_VERSION")===1){const o="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=ua(this.gl,o),yn(this.gl,a))this.textureHalfFloatExtension=ua(this.gl,a);else if(B().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(s),yn(this.gl,r))this.colorBufferHalfFloatExtension=ua(this.gl,r);else if(B().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(s="EXT_color_buffer_float",yn(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(yn(this.gl,r))this.colorBufferHalfFloatExtension=this.gl.getExtension(r);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=dS(this.gl),this.indexBuffer=pS(this.gl),this.framebuffer=j$(this.gl),this.textureConfig=ny(this.gl,this.textureHalfFloatExtension)}get debug(){return B().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;re(e,()=>e.finish()),re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),re(e,()=>e.deleteFramebuffer(this.framebuffer)),re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),re(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),fS(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),mS(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),gS(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),vS(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,s,r){this.throwIfDisposed(),wS(this.gl,e,t,s,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),bS(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),yS(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Dd(this.gl,this.framebuffer),this.outputTexture=null),re(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,s){return this.downloadMatrixDriver(e,()=>IS(this.gl,t,s,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,s,r,o,a){return NS(this.gl,e,t,s,r,o,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return SS(this.gl,e,t)}createBufferFromTexture(e,t,s){this.bindTextureToFrameBuffer(e);const r=$S(this.gl,t,s,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,s;if(B().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,o=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),s=()=>{const a=r.clientWaitSync(o,0,0);return a===r.ALREADY_SIGNALED||a===r.CONDITION_SATISFIED},t=o}else B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(t,B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:t,isFencePassed:s}}downloadMatrixFromPackedTexture(e,t,s){return this.downloadMatrixDriver(e,()=>CS(this.gl,t,s))}createProgram(e){this.throwIfDisposed();const t=this.gl;this.vertexShader==null&&(this.vertexShader=hS(t));const s=B$(t);re(t,()=>t.attachShader(s,this.vertexShader)),re(t,()=>t.attachShader(s,e)),V$(t,s);const r=Object.assign(s,{vao:this.createVertexArray()});return this.debug&&Cl(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;re(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),xS(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(re(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Cl(this.gl,this.program),re(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,s=!0){return this.throwIfDisposed(),s?K$(this.gl,e,t):X$(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),re(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,s){this.throwIfDisposed(),this.throwIfNoProgram(),Y$(this.gl,e,t,s)}setOutputMatrixTexture(e,t,s){this.setOutputMatrixTextureDriver(e,s,t)}setOutputPackedMatrixTexture(e,t,s){this.throwIfDisposed();const[r,o]=Uo(t,s);this.setOutputMatrixTextureDriver(e,r,o)}setOutputMatrixWriteRegion(e,t,s,r){this.setOutputMatrixWriteRegionDriver(s,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,s,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Cl(this.gl,this.program),ca(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}re(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),re(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=ua(this.gl,B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const s=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=s.createQuery();return s.beginQuery(r.TIME_ELAPSED_EXT,o),o}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,s=this.getQueryTimerExtensionWebGL2();t.endQuery(s.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await Bh(()=>this.disposed||this.isQueryAvailable(e,B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const s=this.gl;return s.getQueryParameter(e,s.QUERY_RESULT)/1e6}else{const s=this.getQueryTimerExtensionWebGL1();return s.getQueryObjectEXT(e,s.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const s=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=s.getQueryParameter(e,s.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}else{const s=this.getQueryTimerExtensionWebGL1(),r=s.getQueryObjectEXT(e,s.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),r&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=JH(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:s}=this.itemsToPoll[t];s()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let s;"setTimeoutCustom"in B().platform&&(s=B().platform.setTimeoutCustom.bind(B().platform)),Bh(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,s)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),kl(this.gl,e,this.framebuffer),this.debug&&ca(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(kl(this.gl,this.outputTexture,this.framebuffer),this.debug&&ca(this.gl)):Dd(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const s=t();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(e,t,s){this.throwIfDisposed();const r=this.gl;kl(r,e,this.framebuffer),this.debug&&ca(r),this.outputTexture=e,re(r,()=>r.viewport(0,0,t,s)),re(r,()=>r.scissor(0,0,t,s))}setOutputMatrixWriteRegionDriver(e,t,s,r){this.throwIfDisposed(),re(this.gl,()=>this.gl.scissor(e,t,s,r))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function JH(n){let e=0;for(;e`${n}.${t}`)}function Wt(n,e){return e===1?[n]:AS(n,e)}function Gj(n,e){if(n===1)return"rc";let t="";for(let s=0;s ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let s=this.rank-2;s= ${this.enableShapeUniforms?`outShape[${s}]`:this.outputShape[s]}`,s= ${s}; + bool rEdge = rp1 >= ${r}; + `}getOutput(e){const t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}), + cEdge ? 0. : getA(${t[1]}), + rEdge ? 0. : getA(${t[2]}), + rEdge || cEdge ? 0. : getA(${t[3]})`}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class RS{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length);let s="";for(let r=0;r<4;r++){let o="thisRC = rc;";r%2===1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),s+=` + ${o} + ${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""} + int flatIndex = getFlatIndex(thisRC); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex); + vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${r}] = + getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); + ${r>0?"}":""} + `}this.userCode=` + ${jj(t,this.enableShapeUniforms)} + ${this.enableShapeUniforms?oy():ry(e)} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.); + + ivec3 thisRC; + int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]}; + int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]}; + + ${s} + + setOutput(result); + } + `}}function jj(n,e){return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${e?aH(["r","c","d"],"inputShape"):so(["r","c","d"],n)} + return ivec3(r, c, d); + } + `}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qj{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,s){const r=Vb(t,s),o=Wb(e,r,s);o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]);const a=Bb(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const l=this.freeTextures[o].pop();return this.usedTextures[o].push(l),l}let i;return r===kt.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===kt.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===kt.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===kt.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===kt.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[o].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,s,r){if(this.freeTextures==null)return;const o=Vb(s,r),a=Wb(t,o,r);a in this.freeTextures||(this.freeTextures[a]=[]);const i=Bb(t,o,this.gpgpu.gl,this.gpgpu.textureConfig,r),l=B().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const u=this.usedTextures[a],c=u&&u.indexOf(e);if(c==null||c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[c]=u[u.length-1],u.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function Kj(n,e){const t=n;if(e===t.R32F)return 4;if(e===t.R16F)return 2;if(e===t.RGBA32F)return 16;if(e===n.RGBA)return 16;if(e===t.RGBA16F)return 8;if(e===t.RGBA8)return 4;throw new Error(`Unknown internal format ${e}`)}function Bb(n,e,t,s,r){const o=Xj(e,s);let a;if(r){const[l,u]=Uo(n[0],n[1]);a=l*u}else{const[l,u]=Yi(n[0],n[1]);a=l*u}const i=Kj(t,o);return a*i}function Xj(n,e){switch(n){case kt.PACKED_2X2_FLOAT32:return cy(e);case kt.PACKED_2X2_FLOAT16:return hy(e);case kt.UNPACKED_FLOAT32:return iy(e);case kt.UNPACKED_FLOAT16:return ly(e);case kt.PACKED_4X1_UNSIGNED_BYTE:return uy(e);default:throw new Error(`Unknown physical texture type ${n}`)}}function Yj(n){return B().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?kt.PACKED_2X2_FLOAT32:kt.UNPACKED_FLOAT32:n?kt.PACKED_2X2_FLOAT16:kt.UNPACKED_FLOAT16}function Vb(n,e){if(n===gn.UPLOAD)return kt.PACKED_2X2_FLOAT32;if(n===gn.RENDER||n==null)return Yj(e);if(n===gn.DOWNLOAD||n===gn.PIXELS)return kt.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function Wb(n,e,t){return`${n[0]}_${n[1]}_${e}_${t}`}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ts{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length),this.userCode=` + float unaryOperation(float x) { + ${t} + } + + void main() { + float x = getAAtOutCoords(); + float y = unaryOperation(x); + + setOutput(y); + } + `}}const _n="if (isnan(x)) return x;",Zj="return x;",Ub="return abs(x);",Jj="return (x >= 0.0) ? x : (exp(x) - 1.0);",Qj=_n+` + return (x < 0.0) ? 0.0 : x; +`,eq=_n+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,Vs="return x;",tq="return 1.0 / (1.0 + exp(-1.0 * x));";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nq="return x;",sq=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,rq=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,oq=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,aq="return 1.0 / (1.0 + exp(-1.0 * x));";class Hs{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length),this.userCode=` + vec4 unaryOperation(vec4 x) { + ${t} + } + + void main() { + vec4 x = getAAtOutCoords(); + vec4 y = unaryOperation(x); + + setOutput(y); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class iq{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Mt(this.outputShape.length);const t=e.length,s=Wt("rc",t),r=Pe(t),o=Gj(t,s),a=s.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=` + void main() { + ${r} rc = getOutputCoords(); + vec4 packedInput = getA(${o}); + + setOutput(getChannel(packedInput, ${i})); + } + `}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lq=_c,uq=1e-7,cq=1e-4,fl={};function hq(n){return n in fl||(fl[n]={}),fl[n]}const dq=B().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),pq=600;function fq(){return B().global.screen==null?1024:B().global.screen.height*B().global.screen.width*window.devicePixelRatio*pq/1024/1024}class gh extends zd{nextDataId(){return gh.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!B().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof zh)t=e;else{const s=qn(B().getNumber("WEBGL_VERSION"),e);t=new zh(s)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const s=qn(B().getNumber("WEBGL_VERSION"));t=new zh(s),this.binaryCache=hq(B().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new qj(this.gpgpu),this.numMBBeforeWarning=fq(),this.texData=new lx(this,Yn())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,s,r,o,a){const i=this.makeTensorInfo(t,s),l=this.texData.get(i.dataId);l.isPacked=!1,l.texture={texture:e,texShape:[r,o]},l.texShape=[r,o];const u=ha(t),c=new Mb(u,!1,a),h=this.runWebGLProgram(c,[i],s,[[r,o]]);return h.shape=t,l.texture=null,this.disposeIntermediateTensorInfo(i),h.dataId}write(e,t,s){if((B().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||B().getBool("DEBUG"))&&this.checkNumericalProblems(e),s==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:s,values:e,usage:gn.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,s,r,o){if(B().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:s,dtype:r,values:t,usage:gn.UPLOAD,refCount:o})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:s,dtype:r,complexTensorInfos:o,slice:a,shape:i,isPacked:l}=t;if(a!=null){let d;l?d=new Hs(i,Vs):d=new ts(i,Vs);const p=this.runWebGLProgram(d,[{dataId:e,shape:i,dtype:r}],r),f=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),f}if(s!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return s;const u=this.activeTimers!=null;let c;u&&(c=Nt());let h;if(r==="complex64"){const d=this.readSync(o.real.dataId),p=this.readSync(o.imag.dataId);h=ks(d,p)}else h=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=Nt()-c),this.convertAndCacheOnCPU(e,h)}async read(e){if(this.pendingRead.has(e)){const f=this.pendingRead.get(e);return new Promise(g=>f.push(g))}const t=this.texData.get(e),{values:s,shape:r,slice:o,dtype:a,complexTensorInfos:i,isPacked:l}=t;if(o!=null){let f;l?f=new Hs(r,Vs):f=new ts(r,Vs);const g=this.runWebGLProgram(f,[{dataId:e,shape:r,dtype:a}],a),m=this.read(g.dataId);return this.disposeIntermediateTensorInfo(g),m}if(s!=null)return this.convertAndCacheOnCPU(e);if(B().getBool("DEBUG")&&!B().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&B().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,c;if(a!=="complex64"&&B().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);const f=this.texData.get(c.dataId);u=this.gpgpu.createBufferFromTexture(f.texture.texture,...dl(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let h;if(a==="complex64"){const f=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),g=f[0],m=f[1];h=ks(g,m)}else if(u==null)h=this.getValuesFromTexture(e);else{const f=G(r);h=this.gpgpu.downloadFloat32MatrixFromBuffer(u,f)}if(c!=null&&this.disposeIntermediateTensorInfo(c),u!=null){const f=this.gpgpu.gl;re(f,()=>f.deleteBuffer(u))}const d=this.convertAndCacheOnCPU(e,h),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(f=>f(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Yn().removeDataId(e,this),this.pendingDeletes--),d}readToGPU(e,t={}){const s=this.texData.get(e),{values:r,shape:o,slice:a,dtype:i,isPacked:l,texture:u}=s;if(i==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(a!=null){let p;l?p=new Hs(o,Vs):p=new ts(o,Vs);const f=this.runWebGLProgram(p,[{dataId:e,shape:o,dtype:i}],i),g=this.readToGPU(f,t);return this.disposeIntermediateTensorInfo(f),g}if(u==null)throw r!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const c=this.decode(e,t.customTexShape),h=Yn().makeTensorFromTensorInfo(c),d=this.texData.get(c.dataId);return Object.assign({tensorRef:h},d.texture)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string")try{const s=t.map(r=>Ss(r));return ve(e.shape,e.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return ve(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e!=null)for(let t=0;t0}time(e){const t=this.activeTimers,s=[];let r=!1;this.programTimersStack==null?(this.programTimersStack=s,r=!0):this.activeTimers.push(s),this.activeTimers=s,e();const o=is(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=is(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,r&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const l=await Promise.all(o);i.kernelMs=ux(l),i.getExtraProfileInfo=()=>l.map((u,c)=>({name:a[c],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Nt(),endMs:null}}endTimer(e){return B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Nt(),e)}async getQueryTime(e){if(B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:s}=this.texData.get(e);return s!=null&&(this.disposeData(s.real.dataId,t),this.disposeData(s.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:s,texShape:r,usage:o,isPacked:a,slice:i}=this.texData.get(e),l=i&&i.origDataId||e,u=this.dataRefCount.get(l);u>1?this.dataRefCount.set(l,u-1):(this.dataRefCount.delete(l),t!=null&&(this.numBytesInGPU-=this.computeBytes(r,s),this.textureManager.releaseTexture(t,r,o,a)));const c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=dq){return B().getBool("WEBGL_CPU_FORWARD")&&e.every(s=>this.texData.get(s.dataId).texture==null&&G(s.shape)0&&es(s[0])){const o=s.map(a=>ns(a));r=this.write(o,e,t)}else r=this.write(s,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,s){return Yn().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,s),this)}unpackTensor(e){const t=new iq(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new Hj(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const s=[Gr(e.shape),...Hr(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},o=[Gr(t),...Hr(t)],a=new RS(o,s),i=!0,l=[s],u=this.runWebGLProgram(a,[r],e.dtype,l,i);return{dataId:u.dataId,shape:t,dtype:u.dtype}}decode(e,t){const s=this.texData.get(e),{isPacked:r,shape:o,dtype:a}=s;if(t!=null){const d=G(o),p=t[0]*t[1]*4;I(d<=p,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}const i=ha(o);let l;r?l=new qH(i):l=new jH(i);const u=!0,c=[t??dl(i)],h=this.runWebGLProgram(l,[{shape:i,dtype:a,dataId:e}],a,c,u,t);return{dtype:a,shape:o,dataId:h.dataId}}runWebGLProgram(e,t,s,r,o=!1,a){const i=this.makeTensorInfo(e.outputShape,s),l=this.texData.get(i.dataId);if(e.packedOutput&&(l.isPacked=!0),e.outPackingScheme===Ta.DENSE){const y=a??dl(e.outputShape);l.texShape=y.map(b=>b*2)}if(e.outTexUsage!=null&&(l.usage=e.outTexUsage),G(i.shape)===0)return l.values=wt(i.dtype,0),i;const u=[],c=t.map(y=>{if(y.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let b=this.texData.get(y.dataId);if(b.texture==null){if(!e.packedInputs&&G(y.shape)<=B().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:y.shape,texData:null,isUniform:!0,uniformValues:b.values};e.packedInputs&&(b.isPacked=!0,b.shape=y.shape)}if(this.uploadToGPU(y.dataId),!!b.isPacked!=!!e.packedInputs)y=b.isPacked?this.unpackTensor(y):this.packTensor(y),u.push(y),b=this.texData.get(y.dataId);else if(b.isPacked&&!Ea(b.shape,y.shape)){const w=y,x=y.shape;y.shape=b.shape,y=this.packedReshape(y,x),u.push(y),b=this.texData.get(y.dataId),w.shape=x}return{shape:y.shape,texData:b,isUniform:!1}});this.uploadToGPU(i.dataId);const h={shape:i.shape,texData:l,isUniform:!1},d=HH(e,c,h),p=this.getAndSaveBinary(d,()=>UH(this.gpgpu,e,c,h)),f=this.activeTimers!=null;let g;f&&(g=this.startTimer()),B().get("ENGINE_COMPILE_ONLY")||GH(this.gpgpu,p,c,h,r),u.forEach(y=>this.disposeIntermediateTensorInfo(y)),f&&(g=this.endTimer(g),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(g)}));const m=B().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const y=Nt();y-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=y)}if(!B().getBool("WEBGL_LAZILY_UNPACK")&&l.isPacked&&o===!1){const y=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),y}return i}compileAndRun(e,t,s,r,o=!1){return s=s||t[0].dtype,this.runWebGLProgram(e,t,s,r,o)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(B().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=z(()=>{if(!B().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=B().getBool("DEBUG");B().set("DEBUG",!1);const t=this.abs(pe(1e-8)).dataSync()[0];if(B().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?uq:cq}uploadToGPU(e){const t=this.texData.get(e),{shape:s,dtype:r,values:o,texture:a,usage:i,isPacked:l}=t;if(a!=null)return;const u=this.activeTimers!=null;let c;u&&(c=Nt());let h=t.texShape;if(h==null&&(h=Q$(s,l),t.texShape=h),o!=null){const d=ha(s);let p,f=h[1],g=h[0];const m=o instanceof Uint8Array||o instanceof Uint8ClampedArray;(l||!m)&&([f,g]=Uo(h[0],h[1])),l?p=new ZH(d,m):p=new Mb(d,m);const y=m?[g,f]:h,b=this.makeTensorInfo(y,r),w=this.texData.get(b.dataId);m?w.usage=gn.PIXELS:w.usage=gn.UPLOAD,w.texShape=y,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),f,g,o);const x=[[g,f]],C=this.runWebGLProgram(p,[b],r,x,!0),E=this.texData.get(C.dataId);t.texShape=E.texShape,t.isPacked=E.isPacked,t.usage=E.usage,B().get("ENGINE_COMPILE_ONLY")?this.disposeData(C.dataId):(t.texture=E.texture,t.values=null,this.texData.delete(C.dataId)),this.disposeIntermediateTensorInfo(b),u&&(this.uploadWaitMs+=Nt()-c)}else{const d=this.acquireTexture(h,i,r,l);t.texture=d}}convertAndCacheOnCPU(e,t){const s=this.texData.get(e),{dtype:r}=s;return t!=null&&(s.values=mq(t,r)),s.values}acquireTexture(e,t,s,r){if(this.numBytesInGPU+=this.computeBytes(e,s),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${o} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*fa(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(const[,t]of Object.entries(this.binaryCache)){const s=new Promise(r=>{try{this.checkCompletion_(t),r(!0)}catch(o){throw o}});e.push(s)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await k0(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(sy(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:s,infLoc:r,nanLoc:o,outShapeLocation:a,outShapeStridesLocation:i,outTexShapeLocation:l}=cS(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=s,e.infLoc=r,e.nanLoc=o,e.outShapeLocation=a,e.outShapeStridesLocation=i,e.outTexShapeLocation=l}}createTensorFromGPUData(e,t,s){e.channels=e.channels||"RGBA";const{texture:r,height:o,width:a,channels:i}=e,l=Yn().backend;if(!l.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const u=l.writeTexture(r,t,s,o,a,i);return Yn().makeTensorFromDataId(u,t,s,l)}}gh.nextDataId=0;function mq(n,e){if(e==="float32"||e==="complex64")return n;if(e==="int32"||e==="bool"){const t=e==="int32"?new Int32Array(n.length):new Uint8Array(n.length);for(let s=0;snew gh,2);const a9={forceHalfFloat:yq};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const py=` + if (isnan(a)) return a; + if (isnan(b)) return b; +`;class jr{constructor(e,t,s){this.variableNames=["A","B"],this.outputShape=ye(t,s),this.enableShapeUniforms=Mt(this.outputShape.length),this.userCode=` + float binaryOperation(float a, float b) { + ${e} + } + + void main() { + float a = getAAtOutCoords(); + float b = getBAtOutCoords(); + setOutput(binaryOperation(a, b)); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oo=` + result.r = isNaN.r ? NAN : result.r; + result.g = isNaN.g ? NAN : result.g; + result.b = isNaN.b ? NAN : result.b; + result.a = isNaN.a ? NAN : result.a; +`;class Xo{constructor(e,t,s,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ye(t,s);const o=this.outputShape.length;this.enableShapeUniforms=Mt(o);let a="";if(r)if(o===0||G(this.outputShape)===1)a=` + result.y = 0.; + result.z = 0.; + result.w = 0.; + `;else if(a=` + ${Pe(o)} coords = getOutputCoords(); + `,o===1)this.enableShapeUniforms?a+=` + result.y = (coords + 1) >= outShape ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `:a+=` + result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `;else{const l=Wt("coords",o);this.enableShapeUniforms?a+=` + bool nextRowOutOfBounds = + (${l[o-2]} + 1) >= outShape[${o} - 2]; + bool nextColOutOfBounds = + (${l[o-1]} + 1) >= outShape[${o} - 1]; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `:a+=` + bool nextRowOutOfBounds = + (${l[o-2]} + 1) >= ${this.outputShape[o-2]}; + bool nextColOutOfBounds = + (${l[o-1]} + 1) >= ${this.outputShape[o-1]}; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `}this.userCode=` + vec4 binaryOperation(vec4 a, vec4 b) { + ${e} + } + + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + + vec4 result = binaryOperation(a, b); + ${a} + + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cn(n){const{inputs:e,backend:t}=n,{x:s}=e;return t.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const bq={kernelName:Qa,backendName:"webgl",kernelFunc:cn};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gr(n){const{inputs:e,backend:t}=n,{real:s,imag:r}=e,o=t.makeTensorInfo(s.shape,"complex64"),a=t.texData.get(o.dataId),i=cn({inputs:{x:s},backend:t}),l=cn({inputs:{x:r},backend:t});return a.complexTensorInfos={real:i,imag:l},o}const xq={kernelName:Yd,backendName:"webgl",kernelFunc:gr};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DS="return (a < 0.) ? b * a : a;",OS=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function wq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{alpha:o}=s,a=t.makeTensorInfo([],"float32",As(o,"float32")),i=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Xo(OS,r.shape,a.shape):new jr(DS,r.shape,a.shape),l=t.runWebGLProgram(i,[r,a],"float32");return t.disposeIntermediateTensorInfo(a),l}const vq={kernelName:Ou,backendName:"webgl",kernelFunc:wq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _S="return (a < 0.) ? b * a : a;",FS=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function $q(n){const{inputs:e,backend:t}=n,{x:s,alpha:r}=e,o=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Xo(FS,s.shape,r.shape):new jr(_S,s.shape,r.shape);return t.runWebGLProgram(o,[s,r],"float32")}const Sq={kernelName:Ju,backendName:"webgl",kernelFunc:$q};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yo="if (isnan(x)) return x;";function Ae({opSnippet:n,packedOpSnippet:e,cpuKernelImpl:t,dtype:s}){return({inputs:r,backend:o})=>{const{x:a}=r,i=o,l=s||a.dtype;if(i.shouldExecuteOnCPU([a])&&t!=null){const h=i.texData.get(a.dataId),d=t(h.values,l);return i.makeTensorInfo(a.shape,l,d)}const u=B().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null;let c;return u?c=new Hs(a.shape,e):c=new ts(a.shape,n),i.runWebGLProgram(c,[a],l)}}function Ft({opSnippet:n,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:o}){return({inputs:a,backend:i})=>{const{a:l,b:u}=a,c=i;if(s&&l.dtype==="complex64"){const f=c.texData.get(l.dataId),g=c.texData.get(u.dataId),[m,y]=[[f.complexTensorInfos.real,g.complexTensorInfos.real],[f.complexTensorInfos.imag,g.complexTensorInfos.imag]].map(w=>{const[x,$]=w,C={dataId:x.dataId,dtype:x.dtype,shape:l.shape},E={dataId:$.dataId,dtype:$.dtype,shape:u.shape},A=new jr(n,l.shape,u.shape);return c.runWebGLProgram(A,[C,E],an(x.dtype,$.dtype))}),b=gr({inputs:{real:m,imag:y},backend:c});return c.disposeIntermediateTensorInfo(m),c.disposeIntermediateTensorInfo(y),b}const h=o||an(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||c.shouldExecuteOnCPU([l,u]))&&r!=null){const f=c.texData.get(l.dataId).values,g=c.texData.get(u.dataId).values,m=l.dtype==="string"?Ts(f):f,y=l.dtype==="string"?Ts(g):g,[b,w]=r(l.shape,u.shape,m,y,h),x=c.makeTensorInfo(w,h),$=c.texData.get(x.dataId);return $.values=b,x}const d=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null;let p;return d?p=new Xo(e,l.shape,u.shape,t):p=new jr(n,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function Aa(n,e=!1){if(n==="linear")return e?nq:Zj;if(n==="relu")return e?rq:Qj;if(n==="elu")return e?sq:Jj;if(n==="relu6")return e?oq:eq;if(n==="prelu")return e?FS:_S;if(n==="leakyrelu")return e?OS:DS;if(n==="sigmoid")return e?aq:tq;throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class LS{constructor(e,t,s,r=!1,o=!1,a=!1,i=null,l=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s,this.enableShapeUniforms=Mt(this.outputShape.length);const c=r?e[1]:e[2],h=Math.ceil(c/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=o?"rc.z, i * 2":"i * 2, rc.z",f=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],g=o?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",y="";i&&(l?m=`vec4 activation(vec4 a) { + vec4 b = getPreluActivationWeightsAtOutCoords(); + ${i} + }`:u?m=`vec4 activation(vec4 a) { + vec4 b = getLeakyreluAlphaAtOutCoords(); + ${i} + }`:m=`vec4 activation(vec4 x) { + ${i} + }`,y="result = activation(result);");const b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let w="rc.x",x="rc.x";e[0]`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);const c=a.texData.get(r.dataId);return c.isPacked&&!Ea(r.shape,l)&&!(c.texture!==null&&Ea(c.shape,l))?Nq(r,l,a):(a.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}const Cq={kernelName:ec,backendName:"webgl",kernelFunc:se};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qb{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:r,inSize:o,outSize:a}=e;this.outputShape=[r,a];const i=Math.floor(s/4)*4,l=s%4;let u="sumValue += dot(values, ones);";if(t!=null){const h=1/t;u=`sumValue += dot(values * ${Rr(h)?h.toPrecision(2):h}, ones);`}let c="";o%s>0&&(c=` + if (inIdx < 0 || inIdx >= ${o}) { + return 0.0; + } + `),this.userCode=` + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${c} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${s}; + + float sumValue = 0.0; + + for (int i = 0; i < ${i}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${u} + } + + int inIdx = inOffset + ${i}; + if (${l===1}) { + vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0); + + ${u} + } else if (${l===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), 0.0, 0.0); + + ${u} + } else if (${l===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), 0.0); + + ${u} + } + setOutput(sumValue); + } + `}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class kq{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:r,inSize:o,outSize:a}=e;this.outputShape=[r,a];let i="0.0",l="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",l="min"):t==="max"&&(i="-1.0 / 1e-20",l="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");const c=Math.floor(s/4)*4,h=s%4;let d=` + if (${t==="sum"}) { + sumValue += dot(values, ones); + } else if (${t==="prod"}) { + vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); + prodValue *= tmp[0] * tmp[1]; + } else { + minMaxValue = ${l}(values, minMaxValue); + if (${t==="min"} || ${t==="max"}) { + minMaxValue = ${l}(values, minMaxValue); + bvec4 isNaN = isnan(values); + if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) { + minMaxValue = vec4(NAN); + } + } + } + `,p="vec4";t==="all"?(i="1.0",d=` + bool reducedAllValue = all(values); + float floatedReducedAllValue = float(reducedAllValue); + allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); + `,p="bvec4"):t==="any"&&(i="0.0",d=` + bool reducedAnyValue = any(values); + float floatedReducedAnyValue = float(reducedAnyValue); + anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); + `,p="bvec4");let f="";o%s>0&&(f=` + if (inIdx < 0 || inIdx >= ${o}) { + return initializationValue; + } + `),this.userCode=` + const float initializationValue = ${i}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${f} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${s}; + + vec4 minMaxValue = vec4(${i}); + float prodValue = 1.0; + float sumValue = 0.0; + float allValue = 1.0; + float anyValue = 0.0; + + for (int i = 0; i < ${c}; i += 4) { + int inIdx = inOffset + i; + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${d} + } + + int inIdx = inOffset + ${c}; + if (${h===1}) { + ${p} values = ${p}( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + ${d} + } else if (${h===2}) { + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + ${d} + } else if (${h===3}) { + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + ${d} + } + setOutput(${u}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tq(n){const e=[];for(;e.length===0||e[e.length-1].outSize!==1;){const t=e.length?e[e.length-1].outSize:n[1],s=Gc(t);e.push({inSize:t,windowSize:s,outSize:Math.ceil(t/s)})}return e}function ao(n,e,t,s){const r=Tq(n.shape);let o=n;for(let a=0;a6)throw Error(`Transpose for rank ${e} is not yet supported`);const t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(e);for(let r=0;r6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=Pe(this.rank),o=AS("rc",this.rank),a=new Array(this.rank);for(let c=0;c`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${n.shape} and ${e.shape} and transposeA=${t} and transposeB=${s} must match.`);const $=t?[y,h,p]:[y,p,h],C=s?[b,f,d]:[b,d,f],E=se({inputs:{x:n},backend:r,attrs:{shape:$}}),A=se({inputs:{x:e},backend:r,attrs:{shape:C}}),k=[E,A],T=Math.max(y,b),S=t?E.shape[1]:E.shape[2],_=o!=null,P=a!=null,V=l==="leakyrelu",M=l!=null?Aa(l,!0):null,W=_||P||V||M!=null;let j;if((p===1||f===1)&&S>PS&&W===!1){let q=E,K=A;t&&(q=Ut({inputs:{x:E},backend:r,attrs:{perm:[0,2,1]}}),k.push(q)),s&&(K=Ut({inputs:{x:A},backend:r,attrs:{perm:[0,2,1]}}),k.push(K));const X=f!==1,J=f===1;let Q=q;X&&(Q=se({inputs:{x:q},backend:r,attrs:{shape:[T,S,1]}}),k.push(Q));const ne=f===1?2:1;let te=K;J&&(te=se({inputs:{x:K},backend:r,attrs:{shape:[T,1,S]}}),k.push(te));const oe=fy({inputs:{a:Q,b:te},backend:r});j=bh({inputs:{x:oe},backend:r,attrs:{axis:ne,keepDims:!0}}),k.push(oe)}else{const q=an(n.dtype,e.dtype),K=new LS($,C,[T,p,f],t,s,_,M,P,V),X=[E,A];if(o!=null&&X.push(o),P&&X.push(a),V){const J=r.makeTensorInfo([],"float32",As(i,"float32"));X.push(J),k.push(J)}j=r.runWebGLProgram(K,X,q)}const U=se({inputs:{x:j},backend:r,attrs:{shape:x}});k.push(j);for(const q of k)r.disposeIntermediateTensorInfo(q);return U}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fq(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:o,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;return au({a:r,b:o,transposeA:l,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:h,activation:c})}const Lq={kernelName:_l,backendName:"webgl",kernelFunc:Fq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kb="return abs(x);";function Pq(n){const{inputs:e,backend:t}=n,{x:s}=e;if(t.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){const o=t.texData.get(s.dataId),a=TS(o.values);return t.makeTensorInfo(s.shape,s.dtype,a)}let r;return B().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Hs(s.shape,Kb):r=new ts(s.shape,Kb),t.runWebGLProgram(r,[s],s.dtype)}const zq={kernelName:hu,backendName:"webgl",kernelFunc:Pq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mq=_n+` + if (abs(x) > 1.) { + return NAN; + } + return acos(x); +`,Bq=Ae({opSnippet:Mq}),Vq={kernelName:Oa,backendName:"webgl",kernelFunc:Bq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wq=_n+` + if (x < 1.0) return NAN; +return log(x + sqrt(x * x - 1.0));`,Uq=Ae({opSnippet:Wq}),Gq={kernelName:_a,backendName:"webgl",kernelFunc:Uq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xb="return a + b;",Hq=Ft({opSnippet:Xb,packedOpSnippet:Xb,supportsComplex:!0,cpuKernelImpl:QH}),jq={kernelName:Ro,backendName:"webgl",kernelFunc:Hq};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qq{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((o,a)=>`T${a}`);const s=[];this.variableNames.forEach(o=>{s.push(`float v${o} = get${o}AtOutCoords();`)});const r=this.variableNames.map(o=>`v${o}`).join(" + ");this.userCode=` + void main() { + ${s.join(` + `)} + + float result = ${r}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Kq{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((o,a)=>`T${a}`);const s=[];this.variableNames.forEach(o=>{s.push(`vec4 v${o} = get${o}AtOutCoords();`)});const r=this.variableNames.map(o=>`v${o}`).join(" + ");this.userCode=` + void main() { + ${s.join(` + `)} + + vec4 result = ${r}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Al(n){const{inputs:e,backend:t}=n,s=e;if(s.length===1)return cn({inputs:{x:s[0]},backend:t});if(s.length>B().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const l=Math.floor(s.length/2),u=Al({inputs:s.slice(0,l),backend:t}),c=Al({inputs:s.slice(l),backend:t});return Al({inputs:[u,c],backend:t})}const r=s.map(l=>l.dtype).reduce((l,u)=>an(l,u)),o=s.map(l=>l.shape),i=B().getBool("WEBGL_PACK")?new Kq(s[0].shape,o):new qq(s[0].shape,o);return t.runWebGLProgram(i,s,r)}const Xq={kernelName:du,backendName:"webgl",kernelFunc:Al};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s,i=r.shape.length,l=Se(o,r.shape);let u=l;const c=Je(u,i);let h=r;c!=null&&(h=Ut({inputs:{x:r},backend:t,attrs:{perm:c}}),u=st(u.length,i)),Ot("all",u,i);const[d,p]=St(h.shape,u),f=G(p),g=se({inputs:{x:h},backend:t,attrs:{shape:[-1,f]}}),m=ao(g,g.dtype,"all",t);let y;if(a){const b=nt(d,l);y=se({inputs:{x:m},backend:t,attrs:{shape:b}})}else y=se({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(m),c!=null&&t.disposeIntermediateTensorInfo(h),y}const Zq={kernelName:Gd,backendName:"webgl",kernelFunc:Yq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s,i=r.shape.length,l=Se(o,r.shape);let u=l;const c=Je(u,i);let h=r;c!=null&&(h=Ut({inputs:{x:r},backend:t,attrs:{perm:c}}),u=st(u.length,i)),Ot("any",u,i);const[d,p]=St(h.shape,u),f=G(p),g=se({inputs:{x:h},backend:t,attrs:{shape:[-1,f]}}),m=ao(g,g.dtype,"any",t);let y;if(a){const b=nt(d,l);y=se({inputs:{x:m},backend:t,attrs:{shape:b}})}else y=se({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(m),c!=null&&t.disposeIntermediateTensorInfo(h),y}const Qq={kernelName:Hd,backendName:"webgl",kernelFunc:Jq};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class eK{constructor(e,t,s){this.variableNames=["A"];const{windowSize:r,batchSize:o,outSize:a}=e;s||this.variableNames.push("bestIndicesA"),this.outputShape=[o,a];const i=t==="max"?">":"<",l=s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${r}; + + int bestIndex = inOffset; + float bestValue = getA(batch, bestIndex); + + for (int i = 0; i < ${r}; i++) { + int inIdx = ${l}; + float candidate = getA(batch, inIdx); + if (candidate ${i} bestValue) { + bestValue = candidate; + bestIndex = inIdx; + } + } + setOutput(float(bestIndex)); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class tK{constructor(e,t,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,I(e.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const o=e[e.length-1],a=Math.ceil(o/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");const i=this.outputShape,l=i.length,u=Pe(l),c=Wt("coords",l);let h,d;if(a===1){d=l+1;const A=Pe(d);h=` + ${A} sourceLocR = ${A}(${c.join()}, 0); + ++${c[l-1]}; + ${A} sourceLocG = ${A}(${c.join()}, 0); + ++${c[l-2]}; + ${A} sourceLocA = ${A}(${c.join()}, 0); + --${c[l-1]}; + ${A} sourceLocB = ${A}(${c.join()}, 0); + --${c[l-2]};`}else d=l,h=` + ${u} sourceLocR = coords; + ++${c[l-1]}; + ${u} sourceLocG = coords; + ++${c[l-2]}; + ${u} sourceLocA = coords; + --${c[l-1]}; + ${u} sourceLocB = coords; + --${c[l-2]};`;const p=["x","y","z","w","u","v"].slice(0,d),f="."+p[d-1],g=p.map(A=>"int "+A),m=Wt("sourceLocR",d-1).concat("inIdx.r"),y=Wt("sourceLocG",d-1).concat("inIdx.g"),b=Wt("sourceLocB",d-1).concat("inIdx.b"),w=Wt("sourceLocA",d-1).concat("inIdx.a"),x=s==="max"?"greaterThan":"lessThan",$=r?"":` + inIdx = round(vec4(getBestIndicesAChannel(${m.join()}), + getBestIndicesAChannel(${y.join()}), + getBestIndicesAChannel(${b.join()}), + getBestIndicesAChannel(${w.join()})));`,C=`vec4( + getAChannel(${m.join()}), + hasNextCol ? getAChannel(${y.join()}) : 0., + hasNextRow ? getAChannel(${b.join()}) : 0., + hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,E=r?"":` + float getBestIndicesAChannel(${g.join()}) { + return getChannel(getBestIndicesA(${p.join()}), + vec2(${p.slice(-2).join()})); + }`;this.userCode=` + float getAChannel(${g.join()}) { + return getChannel(getA(${p.join()}), + vec2(${p.slice(-2).join()})); + } + ${E} + void main() { + ${u} coords = getOutputCoords(); + bool hasNextCol = ${c[l-1]} < ${i[l-1]-1}; + bool hasNextRow = ${c[l-2]} < ${i[l-2]-1}; + ${h} + ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f}, + sourceLocB${f}, sourceLocA${f}) * ${t}; + ivec4 inIdx = srcIdx; + vec4 bestIndex = vec4(inIdx); + vec4 bestValue = ${C}; + + for (int i = 0; i < ${t}; i++) { + inIdx = srcIdx; + ${$} + vec4 candidate = ${C}; + bvec4 nan = isnan(candidate); + bvec4 replace = bvec4( + vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan))); + + bestValue = vec4(replace.x ? candidate.x : bestValue.x, + replace.y ? candidate.y : bestValue.y, + replace.z ? candidate.z : bestValue.z, + replace.w ? candidate.w : bestValue.w); + bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace)); + srcIdx++; + } + setOutput(bestIndex); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zS(n,e,t,s=null){let r=e.shape[0],o=e.shape[1];s!=null&&(r=s.shape[0],o=s.shape[1]);const a=Gc(o),i={windowSize:a,inSize:o,batchSize:r,outSize:Math.ceil(o/a)},l=new eK(i,t,s==null),u=[e];s!=null&&u.push(s);const c=n.runWebGLProgram(l,u,"int32");if(c.shape[1]===1)return c;const h=zS(n,e,t,c);return n.disposeIntermediateTensorInfo(c),h}function MS(n,e,t,s=null){const r=s!=null?s.shape:e.shape,o=r[r.length-1],a=Gc(o),i=new tK(r,a,t,s==null),l=s==null?[e]:[e,s],u=n.runWebGLProgram(i,l,"int32");if(u.shape.length===e.shape.length){const c=MS(n,e,t,u);return n.disposeIntermediateTensorInfo(u),c}return u}function BS(n,e,t,s){const r=[t];if(Ot("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,e.shape.length),!B().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){const o=[],a=n.texData.get(e.dataId),i=a!==null&&a.isPacked;let l=e;i&&(l=n.unpackTensor(e),o.push(l));const[u,c]=St(l.shape,r),h=G(c),d=se({inputs:{x:l},backend:n,attrs:{shape:[-1,h]}});o.push(d);const p=zS(n,d,s);o.push(p);const f=se({inputs:{x:p},backend:n,attrs:{shape:u}});return o.forEach(g=>n.disposeIntermediateTensorInfo(g)),f}return MS(n,e,s)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o}=s;let a=Se(o,r.shape);const i=Je(a,r.shape.length);let l=r;const u=[];i!=null&&(l=Ut({inputs:{x:r},backend:t,attrs:{perm:i}}),u.push(l),a=st(a.length,l.shape.length)),Ot("argMax",[a[0]],l.shape.length);const c=BS(t,l,a[0],"max");return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),c}const sK={kernelName:pu,backendName:"webgl",kernelFunc:nK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o}=s;let a=Se(o,r.shape);const i=Je(a,r.shape.length);let l=r;const u=[];i!=null&&(l=Ut({inputs:{x:r},backend:t,attrs:{perm:i}}),u.push(l),a=st(a.length,l.shape.length)),Ot("argMin",[a[0]],l.shape.length);const c=BS(t,l,a[0],"min");return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),c}const oK={kernelName:fu,backendName:"webgl",kernelFunc:rK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aK=_n+` + if (abs(x) > 1.) { + return NAN; + } + return asin(x); +`,iK=Ae({opSnippet:aK}),lK={kernelName:Fa,backendName:"webgl",kernelFunc:iK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uK=_n+"return log(x + sqrt(x * x + 1.0));",cK=Ae({opSnippet:uK}),hK={kernelName:La,backendName:"webgl",kernelFunc:cK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dK=_n+` + return atan(x); +`,pK=Ae({opSnippet:dK}),fK={kernelName:Pa,backendName:"webgl",kernelFunc:pK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mK=py+` + return atan(a, b); +`,gK=` + vec4 result = atan(a, b); + bvec4 isNaNA = isnan(a); + bvec4 isNaNB = isnan(b); + bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w); + `+oo+` + return result; +`,yK=Ft({opSnippet:mK,packedOpSnippet:gK}),bK={kernelName:Ma,backendName:"webgl",kernelFunc:yK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xK=_n+` + if ((x < -1.0) || (x > 1.0)) return NAN; +return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,wK=Ae({opSnippet:xK}),vK={kernelName:za,backendName:"webgl",kernelFunc:wK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ra{constructor(e,t,s,r=!1,o=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,f=e.padInfo.left;this.outputShape=e.outShape;const g=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,y=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let b="0.0";if(g||(b="-1.0 / 1e-20"),s){this.userCode=` + const ivec2 strides = ivec2(${i}, ${l}); + const ivec2 pads = ivec2(${p}, ${f}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + float avgValue = 0.0; + + for (int wR = 0; wR < ${h}; + wR += ${u}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${d}; + wC += ${c}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float value = getX(batch, xR, xC, d); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value >= currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${r?o?m:y:`wR * ${d} + wC`}; + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}const w="max";let x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / max(count, 1.0)");const $=Math.floor(a/4)*4,C=a%4,E=` + if (${g}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${w}(values, minMaxValue); + } + `;this.userCode=` + const ivec2 strides = ivec2(${i}, ${l}); + const ivec2 pads = ivec2(${p}, ${f}); + const float initializationValue = ${b}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xR, int xC, int d) { + if (xC < 0 || xC >= ${e.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xR, xC, d); + } + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + vec4 minMaxValue = vec4(${b}); + float avgValue = 0.0; + count = 0.0; + + for (int wR = 0; wR < ${h}; + wR += ${u}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${$}; wC += 4) { + int xC = xCCorner + wC * ${c}; + + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${c}, d), + getValue(batch, xR, xC + 2 * ${c}, d), + getValue(batch, xR, xC + 3 * ${c}, d) + ); + + ${E} + } + + int xC = xCCorner + ${$}; + if (${C===1}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + initializationValue, + initializationValue, + initializationValue + ); + + ${E} + } else if (${C===2}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${c}, d), + initializationValue, + initializationValue + ); + + ${E} + } else if (${C===3}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${c}, d), + getValue(batch, xR, xC + 2 * ${c}, d), + initializationValue + ); + + ${E} + } + } + setOutput(${x}); + } + `}}class my{constructor(e,t,s,r=!1,o=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideDepth,l=e.strideHeight,u=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,f=e.effectiveFilterHeight,g=e.effectiveFilterWidth,m=e.padInfo.front,y=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;const w=t==="avg";let x="0.0";if(w||(x="-1.0 / 1e-20"),s){this.userCode=` + const ivec3 strides = + ivec3(${i}, ${l}, ${u}); + const ivec3 pads = ivec3(${m}, ${y}, ${b}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + + for (int wD = 0; wD < ${p}; + wD += ${c}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${e.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${h}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${g}; + wC += ${d}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float value = getX(batch, xD, xR, xC, ch); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value >= currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${r?o?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${f} * ${g} + + wR * ${g} + wC`}; + } + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}const $="max";let C=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(C="avgValue / max(count, 1.0)");const E=Math.floor(a/4)*4,A=a%4,k=` + if (${w}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${$}(values, minMaxValue); + } + `;this.userCode=` + const ivec3 strides = + ivec3(${i}, ${l}, ${u}); + const ivec3 pads = ivec3(${m}, ${y}, ${b}); + const float initializationValue = ${x}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xD, int xR, int xC, int ch) { + if (xC < 0 || xC >= ${e.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xD, xR, xC, ch); + } + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch). + // ? = to be determined + vec4 minMaxValue = vec4(${x}); + float avgValue = 0.0; + count = 0.0; + + for (int wD = 0; wD < ${p}; + wD += ${c}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${e.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${h}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${E}; wC += 4) { + int xC = xCCorner + wC * ${d}; + + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${d}, ch), + getValue(batch, xD, xR, xC + 2 * ${d}, ch), + getValue(batch, xD, xR, xC + 3 * ${d}, ch) + ); + + ${k} + } + + int xC = xCCorner + ${E}; + if (${A===1}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + initializationValue, + initializationValue, + initializationValue + ); + + ${k} + } else if (${A===2}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${d}, ch), + initializationValue, + initializationValue + ); + + ${k} + } else if (${A===3}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${d}, ch), + getValue(batch, xD, xR, xC + 2 * ${d}, ch), + initializationValue + ); + + ${k} + } + } + } + setOutput(${C}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $K(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e;Go(r,"avgPool");const{filterSize:o,strides:a,pad:i,dimRoundingMode:l}=s,u=1;I(Dt(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);const c=Dn(r.shape,o,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&Ce(c.inShape,c.outShape))return cn({inputs:{x:r},backend:t});const h=new Ra(c,"avg",!1);return t.runWebGLProgram(h,[r],"float32")}const SK={kernelName:mu,backendName:"webgl",kernelFunc:$K};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:o,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=s,c=[1,1,1],h=Rs(r.shape,o,a,c,i,l,u),d=new my(h,"avg",!1);return t.runWebGLProgram(d,[r],"float32")}const NK={kernelName:gu,backendName:"webgl",kernelFunc:IK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class CK{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=l-1-e.padInfo.top,h=u-1-e.padInfo.left,d=1/(t*s);this.userCode=` + const ivec2 pads = ivec2(${c}, ${h}); + const float avgMultiplier = float(${d}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${l}; + wR += ${a}) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${u}; + wC+= ${i}) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + + dotProd += dyValue * avgMultiplier; + } + } + setOutput(dotProd); + } + `}}class kK{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,r=e.filterWidth,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,h=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,f=h-1-e.padInfo.front,g=d-1-e.padInfo.top,m=p-1-e.padInfo.left,y=1/(t*s*r);this.userCode=` + const ivec3 pads = ivec3(${f}, ${g}, ${m}); + const float avgMultiplier = float(${y}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${h}; + wD += ${l}) { + float dyD = float(dyDCorner + wD) / ${o}.0; + + if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${d}; + wR += ${u}) { + float dyR = float(dyRCorner + wR) / ${a}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${p}; + wC += ${c}) { + float dyC = float(dyCCorner + wC) / ${i}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + + dotProd += dyValue * avgMultiplier; + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TK(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o}=e,a=o,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=s,h=[1,1,1],d=Rs(a.shape,i,l,h,u,c),p=new kK(d);return t.runWebGLProgram(p,[r],a.dtype)}const EK={kernelName:qd,backendName:"webgl",kernelFunc:TK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AK(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o}=e,a=o;Go([r,o],"avgPoolGrad");const{filterSize:i,strides:l,pad:u}=s,c=Dn(a.shape,i,l,1,u),h=new CK(c);return t.runWebGLProgram(h,[r],a.dtype)}const RK={kernelName:jd,backendName:"webgl",kernelFunc:AK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DK(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:o}=e,{transposeA:a,transposeB:i}=s;return au({a:r,b:o,transposeA:a,transposeB:i,backend:t})}const OK={kernelName:yu,backendName:"webgl",kernelFunc:DK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _K{constructor(e,t,s,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ye(e,t),ye(e,s);let i="0.0";r!=null&&(ye(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="1.0";o!=null&&(ye(e,o),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` + void main() { + float x = getXAtOutCoords(); + float mean = getMeanAtOutCoords(); + float variance = getVarianceAtOutCoords(); + float offset = ${i}; + float scale = ${l}; + float inv = scale * inversesqrt(variance + float(${a})); + setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class FK{constructor(e,t,s,r,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ye(e,t),ye(e,s);let i="vec4(0.0)";r!=null&&(ye(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="vec4(1.0)";o!=null&&(ye(e,o),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` + void main() { + vec4 offset = ${i}; + vec4 scale = ${l}; + + vec4 x = getXAtOutCoords(); + vec4 mean = getMeanAtOutCoords(); + vec4 variance = getVarianceAtOutCoords(); + + vec4 inv = scale * inversesqrt(variance + vec4(${a})); + + setOutput((x - mean) * inv + offset); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LK=({inputs:n,backend:e,attrs:t})=>{const{x:s,mean:r,variance:o,offset:a,scale:i}=n;I(r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),I(a==null||r.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),I(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=t;l==null&&(l=.001);const u=[s,r,o];let c=null;a!=null&&(c=a.shape,u.push(a));let h=null;i!=null&&(h=i.shape,u.push(i));const d=B().getBool("WEBGL_PACK_NORMALIZATION")?new FK(s.shape,r.shape,o.shape,c,h,l):new _K(s.shape,r.shape,o.shape,c,h,l);return e.runWebGLProgram(d,u,u[0].dtype)},PK={kernelName:Au,backendName:"webgl",kernelFunc:LK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class zK{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Pe(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const s=MK(this.rank);let r;const o=e.map((a,i)=>`sourceLoc.${Fd[i]} = start[${i}] + coords.${Fd[i]};`);r=` + ${t} sourceLoc; + ${t} coords = getOutputCoords(); + ${o.join(` +`)} + `,this.userCode=` + void main() { + ${r} + setOutput(getSource(${s})); + } + `}}const Fd=["x","y","z","w","u","v"];function MK(n){if(n===1)return"sourceLoc";if(n<=6)return Fd.slice(0,n).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class BK{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=Pe(this.rank),s=Wt("coords",this.rank),r=Wt("sourceLoc",this.rank),o=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${o})`,i=` + result.x = ${a}; + if (++${s[this.rank-1]} < ${e[this.rank-1]}) { + ++${r[this.rank-1]}; + result.y = ${a}; + --${r[this.rank-1]}; + } + `,l=this.rank===1?"":` + --${s[this.rank-1]}; + if (++${s[this.rank-2]} < ${e[this.rank-2]}) { + ++${r[this.rank-2]}; + result.z = ${a}; + if (++${s[this.rank-1]} < ${e[this.rank-1]}) { + ++${r[this.rank-1]}; + result.w = ${a}; + } + } + `,u=this.rank<=4?`sourceLoc = coords + + ${t}(${e.map((c,h)=>`start[${h}]`).join()});`:e.map((c,h)=>`${r[h]} = ${s[h]} + start[${h}];`).join(` +`);this.userCode=` + void main() { + ${t} coords = getOutputCoords(); + ${t} sourceLoc; + ${u} + vec4 result = vec4(0.); + ${i} + ${l} + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VK(n,e,t,s){const r=s.texData.get(n.dataId),o=s.makeTensorInfo(t,n.dtype),a=s.texData.get(o.dataId);Object.assign(a,r),a.refCount=1,a.shape=t,a.dtype=n.dtype;let i=Hf(e,he(n.shape));r.slice&&(i+=r.slice.flatOffset),a.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||n.dataId};const l=s.dataRefCount.get(a.slice.origDataId)||1;return s.dataRefCount.set(a.slice.origDataId,l+1),o}function Zo(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:o,size:a}=s,[i,l]=Uc(r,o,a);if(Wf(r,i,l),G(l)===0)return t.makeTensorInfo(l,r.dtype,[]);if(t.shouldExecuteOnCPU([r])||r.dtype==="string"){const h=t.texData.get(r.dataId),d=Rj(h.values,i,l,r.shape,r.dtype);return t.makeTensorInfo(l,r.dtype,d)}const{isPacked:u}=t.texData.get(r.dataId),c=Gf(r.shape,i,l);if(u||!c){const h=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new BK(l):new zK(l),d=[i];return t.runWebGLProgram(h,[r],r.dtype,d)}return t.uploadToGPU(r.dataId),VK(r,i,l,t)}const WK={kernelName:oc,backendName:"webgl",kernelFunc:Zo};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UK=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:o,crops:a}=s;I(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const i=o.reduce((b,w)=>b*w),l=Pi(r.shape,o,i),u=zi(l.length,o.length),c=Mi(r.shape,o,i),h=Yf(a,o.length),d=Zf(c,a,o.length),p=[],f=se({inputs:{x:r},backend:t,attrs:{shape:l}}),g=Ut({inputs:{x:f},backend:t,attrs:{perm:u}}),m=se({inputs:{x:g},backend:t,attrs:{shape:c}}),y=Zo({inputs:{x:m},backend:t,attrs:{begin:h,size:d}});return p.push(f),p.push(g),p.push(m),p.forEach(b=>t.disposeIntermediateTensorInfo(b)),y},GK={kernelName:bu,backendName:"webgl",kernelFunc:UK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:o}=e,{size:a}=s,i=t.readSync(r.dataId),l=t.readSync(o.dataId),u=kS(i,l,o.dtype,o.shape,a);return t.makeTensorInfo([a],o.dtype,u)}const jK={kernelName:Kd,backendName:"webgl",kernelFunc:HK};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qK=` + int r = int(a.r) & int(b.r); + int g = int(a.g) & int(b.g); + int rb = int(a.b) & int(b.b); + int ra = int(a.a) & int(b.a); + return vec4(r, g, rb, ra); +`,KK=` + return float(int(a.r) & int(b.r)); +`;function XK(n){const{inputs:e,backend:t}=n,{a:s,b:r}=e,o=B().getBool("WEBGL_PACK_BINARY_OPERATIONS"),a=B().getNumber("WEBGL_VERSION");if(t.shouldExecuteOnCPU([s,r])||a===1){const l=t.texData.get(s.dataId).values,u=t.texData.get(r.dataId).values,[c,h]=tj(s.shape,r.shape,l,u,s.dtype),d=t.makeTensorInfo(h,s.dtype),p=t.texData.get(d.dataId);return p.values=c,d}let i;return o?i=new Xo(qK,s.shape,r.shape,!1):i=new jr(KK,s.shape,r.shape),t.runWebGLProgram(i,[s,r],s.dtype)}const YK={kernelName:xu,backendName:"webgl",kernelFunc:XK};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZK(n){const{inputs:e,backend:t}=n,{s0:s,s1:r}=e,o=t.readSync(s.dataId),a=t.readSync(r.dataId),i=ye(Array.from(o),Array.from(a));return t.makeTensorInfo([i.length],"int32",Int32Array.from(i))}const JK={kernelName:Xd,backendName:"webgl",kernelFunc:ZK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QK="return float(a != b);",VS=Ft({opSnippet:QK,cpuKernelImpl:$j,dtype:"bool"}),e6={kernelName:qu,backendName:"webgl",kernelFunc:VS};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ji(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.texData.get(s.dataId);return cn({inputs:{x:r.complexTensorInfos.real},backend:t})}const t6={kernelName:Ep,backendName:"webgl",kernelFunc:Ji};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n6="return float(int(x));";function s6(n,e){const t=new ts(n.shape,n6),s=e.runWebGLProgram(t,[n],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ld(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dtype:o}=s;if(o==="complex64"){if(r.dtype==="complex64")return cn({inputs:{x:r},backend:t});const a=ct(r.shape),i=Ld({inputs:{x:r},backend:t,attrs:{dtype:"float32"}}),l=gr({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){const a=Ji({inputs:{input:r},backend:t}),i=Ld({inputs:{x:a},backend:t,attrs:{dtype:o}});return t.disposeIntermediateTensorInfo(a),i}if(!Vd(r.dtype,o)){const a=cn({inputs:{x:r},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(t.shouldExecuteOnCPU([r])){const a=t.texData.get(r.dataId).values,[i,l,u]=nj(a,r.shape,r.dtype,o);return t.makeTensorInfo(i,l,u)}if(o==="int32")return s6(r,t);if(o==="bool"){const a=t.makeTensorInfo([],"bool",wt("bool",1)),l=VS({inputs:{a:r,b:a},backend:t});return t.disposeIntermediateTensorInfo(a),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${o}`)}const r6={kernelName:Ba,backendName:"webgl",kernelFunc:Ld};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yb="return ceil(x);",o6=Ae({opSnippet:Yb,packedOpSnippet:Yb,cpuKernelImpl:sj}),a6={kernelName:Va,backendName:"webgl",kernelFunc:o6};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class i6{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=` + + void main() { + float value = getAAtOutCoords(); + if (isnan(value)) { + setOutput(value); + return; + } + + setOutput(clamp(value, minVal, maxVal)); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class l6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=` + void main() { + vec4 value = getAAtOutCoords(); + + if (any(isnan(value))) { + setOutput(value); + return; + } + + setOutput(clamp(value, vec4(minVal), vec4(maxVal))); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function u6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{clipValueMin:o,clipValueMax:a}=s;let i;B().getBool("WEBGL_PACK_CLIP")?i=new l6(r.shape):i=new i6(r.shape);const l=[[o],[a]];return t.runWebGLProgram(i,[r],r.dtype,l)}const c6={kernelName:Wa,backendName:"webgl",kernelFunc:u6};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class h6{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=` + void main() { + float re = abs(getRealAtOutCoords()); + float im = abs(getImagAtOutCoords()); + float mx = max(re, im); + + // sadly the length function in glsl is not underflow-safe + // (at least not on Intel GPUs). So the safe solution is + // to ensure underflow-safety in all cases. + setOutput( + mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx)) + ); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zb(n,e){return{dataId:e.dataId,dtype:e.dtype,shape:n.shape}}function d6(n){const{inputs:e,backend:t}=n,{x:s}=e,r=t.texData.get(s.dataId),o=new h6(s.shape),a=[Zb(s,r.complexTensorInfos.real),Zb(s,r.complexTensorInfos.imag)];return t.runWebGLProgram(o,a,a[0].dtype)}const p6={kernelName:wu,backendName:"webgl",kernelFunc:d6};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class f6{constructor(e){this.outputShape=[],this.outputShape=rs(e,1),this.variableNames=e.map((a,i)=>`T${i}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a`T${m}`);const l=new Array(e.length-1);l[0]=e[0][t];for(let g=1;g= ${l[g-1]}) { + return getChannel( + getT${g}(${ml(i,u,m)}), + vec2(${ml(c,u,m)})); + }`}const p=l.length,f=l[l.length-1];d+=` + return getChannel( + getT${p}(${ml(i,u,f)}), + vec2(${ml(c,u,f)}));`,this.userCode=` + float getValue(${i.map(g=>"int "+g)}) { + ${d} + } + + void main() { + ${o} coords = getOutputCoords(); + vec4 result = vec4(getValue(${a}), 0., 0., 0.); + + ${a[r-1]} = ${a[r-1]} + 1; + if (${a[r-1]} < ${s[r-1]}) { + result.g = getValue(${a}); + } + + ${a[r-2]} = ${a[r-2]} + 1; + if (${a[r-2]} < ${s[r-2]}) { + result.a = getValue(${a}); + } + + ${a[r-1]} = ${a[r-1]} - 1; + if (${a[r-2]} < ${s[r-2]} && + ${a[r-1]} < ${s[r-1]}) { + result.b = getValue(${a}); + } + setOutput(result); + } + `}}function ml(n,e,t){const s=n.indexOf(e);return n.map((o,a)=>a===s?`${o} - ${t}`:o).join()}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xh(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.texData.get(s.dataId);return cn({inputs:{x:r.complexTensorInfos.imag},backend:t})}const g6={kernelName:mp,backendName:"webgl",kernelFunc:xh};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function da(n,e,t){const s=n[0].dtype;if(s==="complex64"){const p=n.map(b=>Ji({inputs:{input:b},backend:t})),f=n.map(b=>xh({inputs:{input:b},backend:t})),g=da(p,e,t),m=da(f,e,t),y=gr({inputs:{real:g,imag:m},backend:t});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),f.forEach(b=>t.disposeIntermediateTensorInfo(b)),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(m),y}let r=t.shouldExecuteOnCPU(n);if(s==="string"&&(r=!0),r){const p=n.map(x=>{const C=[-1,G(x.shape.slice(e))];return se({inputs:{x},backend:t,attrs:{shape:C}})}),f=p.map(x=>({vals:t.readSync(x.dataId),shape:x.shape})),g=rs(p.map(x=>x.shape),1),m=p[0].shape[0]===1,y=rj(f,g,s,m),b=rs(n.map(x=>x.shape),e),w=t.makeTensorInfo(b,s,y);return p.forEach(x=>t.disposeIntermediateTensorInfo(x)),w}const o=n.filter(p=>G(p.shape)>0),a=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&o[0].shape.length>1;if(o.length===1){const p=a?new ts(n[0].shape,Vs):new Hs(n[0].shape,Vs);return t.runWebGLProgram(p,n,s)}const i=B().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(o.length>i){const p=[];for(let g=0;gf.shape),e);return t.runWebGLProgram(p,o,s)}const{tensors2D:l,outShape:u}=y6(o,e,t),c=new f6(l.map(p=>p.shape)),h=t.runWebGLProgram(c,l,s);l.forEach(p=>t.disposeIntermediateTensorInfo(p));const d=se({inputs:{x:h},attrs:{shape:u},backend:t});return t.disposeIntermediateTensorInfo(h),d}function y6(n,e,t){const s=rs(n.map(o=>o.shape),e);return{tensors2D:n.map(o=>se({inputs:{x:o},attrs:{shape:[-1,G(o.shape.slice(e))]},backend:t})),outShape:s}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WS(n){const{inputs:e,backend:t,attrs:s}=n,{axis:r}=s,o=Se(r,e[0].shape)[0],a=e.map(u=>u.shape);qf(a,o);const i=rs(e.map(u=>u.shape),o);if(G(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);const l=e.filter(u=>G(u.shape)>0);return l.length===1?cn({inputs:{x:l[0]},backend:t}):da(l,o,t)}const b6={kernelName:vu,backendName:"webgl",kernelFunc:WS};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class US{constructor(e,t=!1,s=null,r=!1,o=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const a=e.padInfo.top,i=e.padInfo.left,l=e.strideHeight,u=e.strideWidth,c=e.dilationHeight,h=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,f=Math.floor(e.inChannels/4)*4,g=e.inChannels%4,m=e.dataFormat==="channelsLast",y=m?1:2,b=m?2:3,w=m?3:1;let x="",$="";s&&(r?x=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${s} + }`:o?x=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${s} + }`:x=` + float activation(float x) { + ${s} + } + `,$="result = activation(result);");const C=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),o&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${x} + + const ivec2 strides = ivec2(${l}, ${u}); + const ivec2 pads = ivec2(${a}, ${i}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d2 = coords[${w}]; + + ivec2 xRCCorner = + ivec2(coords[${y}], coords[${b}]) * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${d}; wR++) { + int xR = xRCorner + wR * ${c}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; wC++) { + int xC = xCCorner + wC * ${h}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 wValues = vec4( + getW(wR, wC, d1, d2), + getW(wR, wC, d1 + 1, d2), + getW(wR, wC, d1 + 2, d2), + getW(wR, wC, d1 + 3, d2) + ); + + if (${m}) { + vec4 xValues = vec4( + getX(batch, xR, xC, d1), + getX(batch, xR, xC, d1 + 1), + getX(batch, xR, xC, d1 + 2), + getX(batch, xR, xC, d1 + 3) + ); + dotProd += dot(xValues, wValues); + } else { + vec4 xValues = vec4( + getX(batch, d1, xR, xC), + getX(batch, d1 + 1, xR, xC), + getX(batch, d1 + 2, xR, xC), + getX(batch, d1 + 3, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + } + + if (${g===1}) { + + if (${m}) { + dotProd += + getX(batch, xR, xC, ${f}) * + getW(wR, wC, ${f}, d2); + } else { + dotProd += + getX(batch, ${f}, xR, xC) * + getW(wR, wC, ${f}, d2); + } + + } else if (${g===2}) { + vec2 wValues = vec2( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2) + ); + + if (${m}) { + vec2 xValues = vec2( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1) + ); + dotProd += dot(xValues, wValues); + } else { + vec2 xValues = vec2( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } else if (${g===3}) { + vec3 wValues = vec3( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2), + getW(wR, wC, ${f} + 2, d2) + ); + + if (${m}) { + vec3 xValues = vec3( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1), + getX(batch, xR, xC, ${f} + 2) + ); + dotProd += dot(xValues, wValues); + } else { + vec3 xValues = vec3( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC), + getX(batch, ${f} + 2, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } + } + } + + float result = dotProd; + ${C} + ${$} + setOutput(result); + } + `}}class x6{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,s=e.padInfo.top,r=e.padInfo.left,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,h=e.filterDepth,d=e.filterHeight,p=e.filterWidth,f=Math.floor(e.inChannels/4)*4,g=e.inChannels%4;this.userCode=` + const ivec3 strides = ivec3(${o}, ${a}, ${i}); + const ivec3 pads = ivec3(${t}, ${s}, ${r}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d2 = coords.u; + + ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xFCorner = xFRCCorner.x; + int xRCorner = xFRCCorner.y; + int xCCorner = xFRCCorner.z; + + // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get + // y(yF, yR, yC, d2). ? = to be determined. : = across all + // values in that axis. + float dotProd = 0.0; + for (int wF = 0; wF < ${h}; wF++) { + int xF = xFCorner + wF * ${l}; + + if (xF < 0 || xF >= ${e.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${d}; wR++) { + int xR = xRCorner + wR * ${u}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; wC++) { + int xC = xCCorner + wC * ${c}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3) + ); + vec4 wValues = vec4( + getW(wF, wR, wC, d1, d2), + getW(wF, wR, wC, d1 + 1, d2), + getW(wF, wR, wC, d1 + 2, d2), + getW(wF, wR, wC, d1 + 3, d2) + ); + + dotProd += dot(xValues, wValues); + } + + if (${g===1}) { + dotProd += + getX(batch, xF, xR, xC, ${f}) * + getW(wF, wR, wC, ${f}, d2); + } else if (${g===2}) { + vec2 xValues = vec2( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1) + ); + vec2 wValues = vec2( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (${g===3}) { + vec3 xValues = vec3( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1), + getX(batch, xF, xR, xC, ${f} + 2) + ); + vec3 wValues = vec3( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2), + getW(wF, wR, wC, ${f} + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class GS{constructor(e,t=!1,s=null,r=!1,o=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Mt(this.outputShape.length);const a=e.padInfo.left,i=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,c=e.filterWidth,h=c;let d=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let m=0;m=0 && xR < inDims[0]) { + `;for(let m=0;m<(h+1)/2;m++){const y=m*2;if(d+=` + xC = xCCorner + ${y*l}; + `,i===1){if(y= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) { + xTexelC${y} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${y}.zw = vec2(0.0); + } + xTexelC${y}Ready = 1; + } + `,l===1&&y>0?d+=` + xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy); + `:d+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + previous.zw = vec2(0.0); + } + + xC${y} = vec4(previous.zw, xTexelC${y}.xy); + } else { + xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy); + } + `):d+=` + if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) { + xTexelC${y} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${y}.zw = vec2(0.0); + } + xTexelC${y}Ready = 1; + } + + xC${y} = xTexelC${y}; + `,y+1= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) { + xTexelC${y+1} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${y+1}.zw = vec2(0.0); + } + xTexelC${y+1}Ready = 1; + } + `,l>1?d+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + xC${y+1} = vec4(previous.zw, xTexelC${y+1}.xy); + } else { + xC${y+1} = vec4(0.0, 0.0, xTexelC${y+1}.xy); + } + `:d+=` + xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy); + `):b===1?d+=` + xC${y+1} = xTexelC${y}; + `:d+=` + xCOffset = xC + ${b}; + + if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) { + xTexelC${y+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${y+1}.zw = vec2(0.0); + } + xTexelC${y+1}Ready = 1; + } + + xC${y+1} = xTexelC${y+1}; + `}}else y= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) { + xTexelC${y} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${y}.zw = vec2(0.0); + } + xTexelC${y}Ready = 1; + } + + if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) { + xTexelC${y+1} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= inDims[1]) { + xTexelC${y+1}.zw = vec2(0.0); + } + xTexelC${y+1}Ready = 1; + } + + xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw); + `,y+1= 0 && xCOffset < inDims[1]) { + final = getX(batch, xR, xCOffset, d1); + } + xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy); + `)):(d+=` + if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) { + xTexelC${y} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${y}.zw = vec2(0.0); + } + xTexelC${y}Ready = 1; + } + + xCOffset = xC + strides[1]; + if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) { + xTexelC${y+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${y+1}.zw = vec2(0.); + } + xTexelC${y+1}Ready = 1; + } + + xC${y} = vec4( + xTexelC${y}.xy, xTexelC${y+1}.xy); + `,y+1= 0) { + // Use custom imod instead mod. On Intel GPU, mod may generate + // unexpected value. + // https://github.com/tensorflow/tfjs/issues/5447 + offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1]; + d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) / + inChannels); + + if(d1 < inputShape[${i}] && d1 >= 0) { + + ch = imod(pos, inChannels); + + if (${o}) { + innerDims = vec2(d1, ch); + result[${c*2+h}] = getChannel( + getA(rc.x, d0, int(innerDims.x), + int(innerDims.y)), innerDims); + } else { + innerDims = vec2(d0, d1); + result[${c*2+h}] = getChannel( + getA(rc.x, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + } + `;this.userCode=` + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0); + + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + + ${u} + + ${r.output} = result; + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iu(n,e){const t=n.length;return t>=3?e?[...n.slice(0,-3),n[t-3]*n[t-2],n[t-1]]:[...n.slice(0,-3),n[t-3],n[t-2]*n[t-1]]:!e&&t===1&&n[0]>1?[n[0],1]:null}function HS({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:o=null,leakyreluAlpha:a=0,activation:i=null}){const l=n.shape,u=s.texData.get(n.dataId),c=t.inChannels,h=l[0]*l[1]*l[2],d=t.outChannels,p=t.dataFormat==="channelsLast",f=!1,g=!1;let m;const y=[];if(o!=null){const x=iu(o.shape,p);x!=null&&(o=se({inputs:{x:o},backend:s,attrs:{shape:x}}),y.push(o))}if(r!=null){const x=iu(r.shape,p);x!=null&&(r=se({inputs:{x:r},backend:s,attrs:{shape:x}}),y.push(r))}if(!((h===1||d===1)&&c>PS)&&u.isPacked&&p&&u.texture!=null&&l[2]%2!==0&&Ce(u.shape.slice(-3),l.slice(-3))){const x=l[0]*l[1]*(l[2]+1),$={dataId:n.dataId,shape:[1,x,t.inChannels],dtype:n.dtype},C=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,I(Ea(u.shape,$.shape),()=>`packed reshape ${u.shape} to ${$.shape} isn't free`);const E=se({inputs:{x:e},backend:s,attrs:{shape:[1,t.inChannels,t.outChannels]}});y.push(E);const A=au({a:$,b:E,backend:s,transposeA:f,transposeB:g,bias:r,activation:i,preluActivationWeights:o,leakyreluAlpha:a}),k=s.texData.get(A.dataId);I(k.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=C,k.shape=t.outShape,m=cn({inputs:{x:A},backend:s}),m.shape=t.outShape,y.push(A)}else{const x=t.outHeight*t.outWidth,$=se({inputs:{x:n},backend:s,attrs:{shape:p?[t.batchSize,x,t.inChannels]:[t.batchSize,t.inChannels,x]}}),C=se({inputs:{x:e},backend:s,attrs:{shape:[1,t.inChannels,t.outChannels]}}),E=au({a:p?$:C,b:p?C:$,transposeA:!p,transposeB:g,backend:s,bias:r,activation:i,preluActivationWeights:o,leakyreluAlpha:a});m=se({inputs:{x:E},backend:s,attrs:{shape:t.outShape}}),y.push($),y.push(C),y.push(E)}for(const x of y)s.disposeIntermediateTensorInfo(x);return m}function jS({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:o=null,leakyreluAlpha:a=0,activation:i=null}){const{filterWidth:l,filterHeight:u,inChannels:c,outWidth:h,outHeight:d,dataFormat:p}=t,f=p==="channelsLast",g=l*u*c,m=d*h,y=[t.batchSize,g,m],b=!0,w=!1,x=[];if(o!=null){const U=iu(o.shape,f);U!=null&&(o=se({inputs:{x:o},backend:s,attrs:{shape:U}}),x.push(o))}if(r!=null){const U=iu(r.shape,f);U!=null&&(r=se({inputs:{x:r},backend:s,attrs:{shape:U}}),x.push(r))}const $=se({inputs:{x:e},backend:s,attrs:{shape:[1,g,G(e.shape)/g]}});x.push($);const C=new w6(y,t),E=[n.shape,[t.padInfo.top,t.padInfo.left],[t.strideHeight,t.strideWidth],[t.dilationHeight,t.dilationWidth],[t.inChannels],[t.filterWidth*t.inChannels],[t.outWidth]],A=s.runWebGLProgram(C,[n],"float32",E),k=se({inputs:{x:A},backend:s,attrs:{shape:y}});x.push(A),x.push(k);const T=r!=null,S=o!=null,_=i==="leakyrelu",P=i?Aa(i,!0):null,V=new LS(f?k.shape:$.shape,f?$.shape:k.shape,f?[t.batchSize,m,t.outChannels]:[t.batchSize,t.outChannels,m],b,w,T,P,S,_),M=f?[k,$]:[$,k];if(r&&M.push(r),S&&M.push(o),_){const U=s.makeTensorInfo([],"float32",As(a,"float32"));M.push(U),x.push(U)}const W=s.runWebGLProgram(V,M,"float32"),j=se({inputs:{x:W},backend:s,attrs:{shape:t.outShape}});x.push(W);for(const U of x)s.disposeIntermediateTensorInfo(U);return j}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:o}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=s,h=Ds(l),d=$t(r.shape,o.shape,a,u,i,c,!1,h);let p;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))p=HS({x:r,filter:o,convInfo:d,backend:t});else if(d.strideWidth<=2&&h==="channelsLast"&&B().getBool("WEBGL_EXP_CONV")){const g=new GS(d),m=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];p=t.runWebGLProgram(g,[r,o],"float32",m)}else if(B().getBool("WEBGL_CONV_IM2COL"))p=jS({x:r,filter:o,convInfo:d,backend:t});else{const g=new US(d);p=t.runWebGLProgram(g,[r,o],"float32")}const f=se({inputs:{x:p},backend:t,attrs:{shape:d.outShape}});return t.disposeIntermediateTensorInfo(p),f}const $6={kernelName:$u,backendName:"webgl",kernelFunc:v6};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class S6{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,r=e.padInfo.top,o=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int d2 = coords.w; + + // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int b = 0; b < ${e.batchSize}; b++) { + for (int yR = 0; yR < ${e.outHeight}; yR++) { + int xR = wR + yR * ${t} - ${r}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${e.outWidth}; yC++) { + int xC = wC + yC * ${s} - ${o}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + ${a?`float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC); + float xValue = getX(b, d1, xR, xC); + dotProd += (xValue * dyValue);`} + } + } + } + setOutput(dotProd); + } + `}}class I6{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,r=e.strideHeight,o=e.strideWidth,a=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,l=s-1-e.padInfo.left,u=a?1:2,c=a?2:3,h=a?3:1;this.userCode=` + const ivec2 pads = ivec2(${i}, ${l}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[${h}]; + + ivec2 dyCorner = ivec2(coords[${u}], coords[${c}]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${t}; wR++) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${t} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${s} - 1 - wC; + + for (int d2 = 0; d2 < ${e.outChannels}; d2++) { + + if (${a}) { + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } else { + float xValue = getDy(batch, d2, idyR, idyC); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + + } + } + } + setOutput(dotProd); + } + `}}class N6{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,s=e.strideHeight,r=e.strideWidth,o=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=` + void main() { + ivec5 coords = getOutputCoords(); + int wF = coords.x; + int wR = coords.y; + int wC = coords.z; + int d1 = coords.w; + int d2 = coords.u; + + float dotProd = 0.0; + + for (int b = 0; b < ${e.batchSize}; b++) { + for (int yF = 0; yF < ${e.outDepth}; yF++) { + int xF = wF + yF * ${t} - ${o}; + + if (xF < 0 || xF >= ${e.inDepth}) { + continue; + } + + for (int yR = 0; yR < ${e.outHeight}; yR++) { + int xR = wR + yR * ${s} - ${a}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${e.outWidth}; yC++) { + int xC = wC + yC * ${r} - ${i}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float dyValue = getDy(b, yF, yR, yC, d2); + float xValue = getX(b, xF, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + } + setOutput(dotProd); + } + `}}class C6{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,r=e.filterWidth,o=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=t-1-e.padInfo.front,u=s-1-e.padInfo.top,c=r-1-e.padInfo.left;this.userCode=` + const ivec3 pads = ivec3(${l}, ${u}, ${c}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.u; + + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyFCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + float dotProd = 0.0; + for (int wF = 0; wF < ${t}; wF++) { + float dyF = float(dyFCorner + wF) / ${o}.0; + + if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) { + continue; + } + int idyF = int(dyF); + + int wFPerm = ${t} - 1 - wF; + + for (int wR = 0; wR < ${s}; wR++) { + float dyR = float(dyRCorner + wR) / ${a}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${s} - 1 - wR; + + for (int wC = 0; wC < ${r}; wC++) { + float dyC = float(dyCCorner + wC) / ${i}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${r} - 1 - wC; + + for (int d2 = 0; d2 < ${e.outChannels}; d2++) { + float xValue = getDy(batch, idyF, idyR, idyC, d2); + float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function k6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:o}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,h=Ds(l),d=$t(r.shape,c,a,1,i,u,!1,h),p=new S6(d);return t.runWebGLProgram(p,[r,o],"float32")}const T6={kernelName:Zd,backendName:"webgl",kernelFunc:k6};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class E6{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=Mt(this.outputShape.length);const t=e.filterHeight,s=e.filterWidth,r=t-1-e.padInfo.top,o=s-1-e.padInfo.left;this.userCode=` + const ivec2 pads = ivec2(${r}, ${o}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + + ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + vec4 result = vec4(0.); + for (int wR = 0; wR < ${t}; wR++) { + float dyR = float(dyRCorner + wR) / strides[0]; + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + int wRPerm = ${t} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + int wCPerm = ${s} - 1 - wC; + + float dyC = float(dyCCorner + wC) / strides[1]; + bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0) + && (fract(dyC) == 0.0); + int idyC = int(dyC); + + float dyC2 = float(dyCCorner + wC + 1) / strides[1]; + bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0) + && (fract(dyC2) == 0.0); + int idyC2 = int(dyC2); + + if (idyCVal && idyCVal2) { + for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC, d2); + vec4 dySample2 = (idyC / 2 == idyC2 / 2) ? + dySample : getDy(batch, idyR, idyC2, d2); + + vec2 dyValue = mod(float(idyC), 2.) == 0. ? + dySample.xy : dySample.zw; + result.xy += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + + dyValue = mod(float(idyC2), 2.) == 0. ? + dySample2.xy : dySample2.zw; + result.zw += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } else if (idyCVal) { + for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC, d2); + vec2 dyValue = mod(float(idyC), 2.) == 0. ? + dySample.xy : dySample.zw; + result.xy += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } else if (idyCVal2) { + for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC2, d2); + vec2 dyValue = mod(float(idyC2), 2.) == 0. ? + dySample.xy : dySample.zw; + result.zw += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } + } + } + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A6(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:o}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=s,h=Ds(u),d=$t(a,o.shape,i,1,l,c,!1,h);if(B().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&h==="channelsLast"){const p=[[d.strideHeight,d.strideWidth]],f=new E6(d);return t.runWebGLProgram(f,[r,o],"float32",p)}else{const p=new I6(d);return t.runWebGLProgram(p,[r,o],"float32")}}const R6={kernelName:Su,backendName:"webgl",kernelFunc:A6};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function D6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:o}=e,{strides:a,pad:i,dilations:l}=s,u=ur(r.shape,o.shape,a,l,i),c=new x6(u);return t.runWebGLProgram(c,[r,o],"float32")}const O6={kernelName:Iu,backendName:"webgl",kernelFunc:D6};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:o}=e,{strides:a,pad:i,filterShape:l}=s,u=ur(r.shape,l,a,1,i),c=new N6(u);return t.runWebGLProgram(c,[r,o],"float32")}const F6={kernelName:Jd,backendName:"webgl",kernelFunc:_6};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function L6(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:o}=e,{pad:a,strides:i,inputShape:l}=s,u=ur(l,o.shape,i,1,a),c=new C6(u);return t.runWebGLProgram(c,[r,o],"float32")}const P6={kernelName:Qd,backendName:"webgl",kernelFunc:L6};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const z6=Yo+` + return cos(x); +`,M6=` + vec4 result = cos(x); + bvec4 isNaN = isnan(x); + ${oo} + return result; +`,B6=Ae({opSnippet:z6,packedOpSnippet:M6}),V6={kernelName:Ua,backendName:"webgl",kernelFunc:B6};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const W6=` + float e2x = exp(-x); + return (e2x + 1.0 / e2x) / 2.0; +`,U6=Ae({opSnippet:W6}),G6={kernelName:Ga,backendName:"webgl",kernelFunc:U6};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class H6{constructor(e,t,s,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,i,l,u]=e,[c]=t,[h,d]=s;this.outputShape=[c,h,d,u];const p=r==="bilinear"?1:0,[f,g]=[`${i-1}.0`,`${l-1}.0`],[m,y,b]=h>1?[`${(i-1)/(h-1)}`,"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[w,x,$]=d>1?[`${(l-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${g} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${g}`];this.userCode=` + const float height_ratio = float(${m}); + const float width_ratio = float(${w}); + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int y = coords[1]; + int x = coords[2]; + int d = coords[3]; + + // get box vals + float y1 = getBoxes(b,0); + float x1 = getBoxes(b,1); + float y2 = getBoxes(b,2); + float x2 = getBoxes(b,3); + + // get image in batch index + int bInd = round(getBoxInd(b)); + if(bInd < 0 || bInd >= ${a}) { + return; + } + + float height_scale = ${y}; + float width_scale = ${x}; + + float in_y = ${b}; + if( in_y < 0.0 || in_y > ${f} ) { + setOutput(float(${o})); + return; + } + float in_x = ${$}; + if( in_x < 0.0 || in_x > ${g} ) { + setOutput(float(${o})); + return; + } + + vec2 sourceFracIndexCR = vec2(in_x,in_y); + if(${p} == 1) { + // Compute the four integer indices. + ivec2 sourceFloorCR = ivec2(sourceFracIndexCR); + ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR)); + + float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d); + float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d); + float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d); + float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d); + + vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR); + + float top = topLeft + (topRight - topLeft) * fracCR.x; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; + float newValue = top + (bottom - top) * fracCR.y; + setOutput(newValue); + } else { + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestCR = ivec2(floor( + sourceFracIndexCR + vec2(0.5,0.5))); + float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d); + setOutput(newValue); + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const j6=n=>{const{inputs:e,backend:t,attrs:s}=n,{image:r,boxes:o,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=s,c=new H6(r.shape,o.shape,i,l,u);return t.runWebGLProgram(c,[r,o,a],"float32")},q6={kernelName:tp,backendName:"webgl",kernelFunc:j6};var Da;(function(n){n.Prod="*",n.Sum="+"})(Da||(Da={}));class Jb{constructor(e,t,s,r){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const o=this.outputShape.length,a=this.op===Da.Prod?"1.0":"0.0",i=s?a:`getX(${Qb(o,"coords",this.op)})`,l=this.outputShape[this.outputShape.length-1];let u="",c="";s?(u=r?`end != ${l-1}`:"end != 0",c=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${l}`:"end >= pow2",c=r?"end + pow2":"end - pow2"),this.userCode=` + void main() { + ${Pe(o)} coords = getOutputCoords(); + int end = ${ex(o,"coords",this.op)}; + float val = ${i}; + int pow2 = int(pow(2.0, index)); + if (${u}) { + int idx = ${c}; + ${ex(o,"coords",this.op)} = idx; + val ${this.op}= getX(${Qb(o,"coords",this.op)}); + } + setOutput(val); + } + `}}function Qb(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.x, ${e}.y`;if(n===3)return`${e}.x, ${e}.y, ${e}.z`;if(n===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw new Error(`Cumulative ${t} for rank ${n} is not yet supported`)}function ex(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.y`;if(n===3)return`${e}.z`;if(n===4)return`${e}.w`;throw new Error(`Cumulative ${t} for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qS(n,e,t,s,r,o){const a=e.shape.length,i=Je([s],a);let l=e;i!=null&&(l=Ut({inputs:{x:e},backend:t,attrs:{perm:i}}));const u=st(1,a)[0];if(u!==a-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${s}`);const c=l.shape[u];let h=cn({inputs:{x:l},backend:t});for(let d=0;d<=Math.ceil(Math.log2(c))-1;d++){const p=new Jb(n,l.shape,!1,o),f=[[d]],g=h;h=t.runWebGLProgram(p,[h],h.dtype,f),t.disposeIntermediateTensorInfo(g)}if(r){const d=new Jb(n,l.shape,r,o),p=h;h=t.runWebGLProgram(d,[h],h.dtype),t.disposeIntermediateTensorInfo(p)}if(i!=null){const d=cr(i),p=Ut({inputs:{x:h},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(l),p}return h}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function K6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,exclusive:a,reverse:i}=s;return qS(Da.Prod,r,t,o,a,i)}const X6={kernelName:ep,backendName:"webgl",kernelFunc:K6};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Y6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,exclusive:a,reverse:i}=s;return qS(Da.Sum,r,t,o,a,i)}const Z6={kernelName:Nu,backendName:"webgl",kernelFunc:Y6};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function J6(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:o}=e,{size:a,binaryOutput:i}=s;if(r.shape.length===1){const l=t.readSync(r.dataId),u=t.readSync(o.dataId),c=kS(l,u,o.dtype,o.shape,a);return t.makeTensorInfo([a],o.dtype,c)}else if(r.shape.length===2){const l=t.bufferSync(r),u=t.bufferSync(o),c=ej(l,u,a,i);return t.makeTensorInfo(c.shape,o.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}const Q6={kernelName:np,backendName:"webgl",kernelFunc:J6};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class eX{constructor(e,t,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=s,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int h = ${this.getHeightCoordString()}; + int w = ${this.getWidthCoordString()}; + int d = ${this.getDepthCoordString()}; + + int in_h = h / ${t}; + int offset_h = imod(h, ${t}); + int in_w = w / ${t}; + int offset_w = imod(w, ${t}); + int offset_d = (offset_h * ${t} + offset_w) * + ${this.getOutputDepthSize()}; + int in_d = d + offset_d; + + float result = ${this.getInputSamplingString()}; + setOutput(result); + } + `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockSize:o,dataFormat:a}=s,i=r.shape[0],l=a==="NHWC"?r.shape[1]:r.shape[2],u=a==="NHWC"?r.shape[2]:r.shape[3],c=a==="NHWC"?r.shape[3]:r.shape[1],h=l*o,d=u*o,p=c/(o*o),f=a==="NHWC"?[i,h,d,p]:[i,p,h,d],g=new eX(f,o,a);return t.runWebGLProgram(g,[r],r.dtype)}const nX={kernelName:sp,backendName:"webgl",kernelFunc:tX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class KS{constructor(e,t=!1,s=null,r=!1,o=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Mt(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,l=e.outChannels/e.inChannels;let u="",c="";s&&(r?u=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${s} + }`:o?u=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${s} + }`:u=` + float activation(float x) { + ${s} + } + `,c="result = activation(result);");const h=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),o&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${u} + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + ivec2 xRCCorner = coords.yz * strides - pads; + int d2 = coords.w; + int d1 = d2 / ${l}; + int q = d2 - d1 * ${l}; + + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations. + for (int wR = 0; wR < ${a}; wR++) { + int xR = xRCorner + wR * dilations[0]; + + if (xR < 0 || xR >= inDims[0]) { + continue; + } + + for (int wC = 0; wC < ${i}; wC++) { + int xC = xCCorner + wC * dilations[1]; + + if (xC < 0 || xC >= inDims[1]) { + continue; + } + + float xVal = getX(batch, xR, xC, d1); + float wVal = getW(wR, wC, d1, q); + dotProd += xVal * wVal; + } + } + + float result = dotProd; + ${h} + ${c} + setOutput(result); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class XS{constructor(e,t=!1,s=null,r=!1,o=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Mt(this.outputShape.length);const a=e.outChannels/e.inChannels,i=e.padInfo.left,l=e.strideWidth,u=e.dilationWidth,c=e.filterHeight,h=e.filterWidth,d=h;let p=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let y=0;y=0 && xR < inDims[0]) { + `;for(let y=0;y<(d+1)/2;y++){const b=y*2;if(p+=` + xC = xCCorner + ${b*u}; + `,l===1){if(b= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + `,u===1&&b>0?p+=` + xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy); + `:p+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + previous.zw = vec2(0.0); + } + + xC${b} = vec4(previous.zw, xTexelC${b}.xy); + } else { + xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy); + } + `):p+=` + if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + + xC${b} = xTexelC${b}; + `,b+1= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.0); + } + xTexelC${b+1}Ready = 1; + } + `,u>1?p+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + xC${b+1} = vec4(previous.zw, xTexelC${b+1}.xy); + } else { + xC${b+1} = vec4(0.0, 0.0, xTexelC${b+1}.xy); + } + `:p+=` + xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy); + `):w===1?p+=` + xC${b+1} = xTexelC${b}; + `:p+=` + xCOffset = xC + ${w}; + + if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.0); + } + xTexelC${b+1}Ready = 1; + } + + xC${b+1} = xTexelC${b+1}; + `}}else b= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + + if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.0); + } + xTexelC${b+1}Ready = 1; + } + + xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw); + `,b+1= 0 && xCOffset < inDims[1]) { + final = getX(batch, xR, xCOffset, d1); + } + xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy); + `)):(p+=` + if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) { + xTexelC${b} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${b}.zw = vec2(0.0); + } + xTexelC${b}Ready = 1; + } + + xCOffset = xC + strides[1]; + if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) { + xTexelC${b+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${b+1}.zw = vec2(0.); + } + xTexelC${b+1}Ready = 1; + } + + xC${b} = vec4( + xTexelC${b}.xy, xTexelC${b+1}.xy); + `,b+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);const h=$t(r.shape,o.shape,a,c,i,u,!0);let d;B().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?d=new XS(h):d=new KS(h);const p=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return t.runWebGLProgram(d,[r,o],"float32",p)}const rX={kernelName:Cu,backendName:"webgl",kernelFunc:sX};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oX{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,r=e.padInfo.top,o=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int dm = coords.w; + int d2 = d1 * ${a} + dm; + + float dotProd = 0.0; + + // TO DO: Vec4 over the batch size + for (int b = 0; b < ${e.batchSize}; b++) { + for (int yR = 0; yR < ${e.outHeight}; yR++) { + int xR = wR + yR * ${t} - ${r}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${e.outWidth}; yC++) { + int xC = wC + yC * ${s} - ${o}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + setOutput(dotProd); + } + `}}class aX{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,r=e.strideHeight,o=e.strideWidth,a=t-1-e.padInfo.top,i=s-1-e.padInfo.left,l=e.outChannels/e.inChannels;this.userCode=` + const ivec2 pads = ivec2(${a}, ${i}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + ivec2 dyCorner = coords.yz - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + float dotProd = 0.0; + + for (int wR = 0; wR < ${t}; wR++) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${t} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${s} - 1 - wC; + + // TO DO: Vec4 over the channelMul + for (int dm = 0; dm < ${l}; dm++) { + int d2 = d1 * ${l} + dm; + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:o}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=s,h=$t(r.shape,c,a,i,l,u,!0),d=new oX(h);return t.runWebGLProgram(d,[r,o],"float32")}const lX={kernelName:rp,backendName:"webgl",kernelFunc:iX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uX(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:o}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=s,h=$t(c,o.shape,a,i,l,u,!0),d=new aX(h);return t.runWebGLProgram(d,[r,o],"float32")}const cX={kernelName:op,backendName:"webgl",kernelFunc:uX};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class hX{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; + setOutput(val); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dX(n){const{inputs:e,backend:t}=n,{x:s}=e,r=[...s.shape,...s.shape],o=G(s.shape),a=se({inputs:{x:s},backend:t,attrs:{shape:[o]}}),i=new hX(o),l=t.runWebGLProgram(i,[a],a.dtype),u=se({inputs:{x:l},backend:t,attrs:{shape:r}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}const pX={kernelName:ap,backendName:"webgl",kernelFunc:dX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fX{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:s,padInfo:r,strideHeight:o,strideWidth:a,filterHeight:i,filterWidth:l,dilationHeight:u,dilationWidth:c}=e,{top:h,left:d}=r;this.userCode=` + const ivec2 strides = ivec2(${o}, ${a}); + const ivec2 pads = ivec2(${h}, ${d}); + const float neg_infinity = -3.4e38; + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.w; + ivec2 outTopLeftCorner = + coords.yz * strides - pads; + int hBeg = outTopLeftCorner.x; + int wBeg = outTopLeftCorner.y; + + float curVal = neg_infinity; + for (int h = 0; h < ${i}; h++) { + int hIn = hBeg + h * ${u}; + + if (hIn >= 0 && hIn < ${t}) { + for (int w = 0; w < ${l}; w++) { + int wIn = wBeg + w * ${c}; + + if (wIn >= 0 && wIn < ${s}) { + float xVal = getX(batch, hIn, wIn, d1); + float wVal = getW(h, w, d1); + + float val = xVal + wVal; + if (val > curVal) { + curVal = val; + } + } + } + } + } + + float result = curVal; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:o}=e,{strides:a,pad:i,dilations:l}=s,u=Ai(r.shape,o.shape,a,i,"NHWC",l);let c;const h=new fX(u);c=t.runWebGLProgram(h,[r,o],"float32");const d=se({inputs:{x:c},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(c),d}const gX={kernelName:ku,backendName:"webgl",kernelFunc:mX};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yX(n){const{inputs:e,backend:t,attrs:s}=n,{equation:r}=s,o=e,{allDims:a,summedDims:i,idDims:l}=om(r,o.length);im(a.length,l,o);const{path:u,steps:c}=lm(i,l),h=c.length;let d=null,p=a.length;const f=[];for(let g=0;g=0&&(d=bh({inputs:{x:d},backend:t,attrs:{axis:u[g]-(a.length-p),keepDims:!1}}),f.push(d)),p--)}for(const g of f)g!==d&&t.disposeIntermediateTensorInfo(g);return d}const bX={kernelName:lp,backendName:"webgl",kernelFunc:yX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xX="return (x >= 0.0) ? x : (exp(x) - 1.0);",wX=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,vX=Ae({opSnippet:xX,packedOpSnippet:wX}),$X={kernelName:ja,backendName:"webgl",kernelFunc:vX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SX="return (b >= 0.0) ? a : a * (b + 1.0);",IX=` + vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); + return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); +`,NX=n=>{const{inputs:e,backend:t}=n,{dy:s,y:r}=e,o=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Xo(IX,s.shape,r.shape):new jr(SX,s.shape,r.shape);return t.runWebGLProgram(o,[s,r],s.dtype)},CX={kernelName:up,backendName:"webgl",kernelFunc:NX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kX=` + return vec4(equal(a, b)); +`,TX="return float(a == b);",EX=Ft({opSnippet:TX,packedOpSnippet:kX,dtype:"bool",cpuKernelImpl:oj}),AX={kernelName:Tu,backendName:"webgl",kernelFunc:EX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RX=` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + float p = ${Jf}; + float a1 = ${Qf}; + float a2 = ${em}; + float a3 = ${tm}; + float a4 = ${nm}; + float a5 = ${sm}; + + float sign = sign(x); + x = abs(x); + float t = 1.0 / (1.0 + p * x); + return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)); +`,DX=Ae({opSnippet:RX}),OX={kernelName:qa,backendName:"webgl",kernelFunc:DX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _X=Yo+` + return exp(x); +`,FX=` + vec4 result = exp(x); + bvec4 isNaN = isnan(x); + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,YS=Ae({opSnippet:_X,packedOpSnippet:FX,cpuKernelImpl:aj,dtype:"float32"}),LX={kernelName:Ka,backendName:"webgl",kernelFunc:YS};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pd(n){const{inputs:e,attrs:t,backend:s}=n,{dim:r}=t,{input:o}=e,a=o.shape.length,i=o.shape.slice();let l=r;return r<0&&(I(-(a+1)<=r,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+r+1),i.splice(l,0,1),se({inputs:{x:o},backend:s,attrs:{shape:i}})}const PX={kernelName:Eu,backendName:"webgl",kernelFunc:Pd};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tx="return exp(x) - 1.0;",zX=Ae({opSnippet:tx,packedOpSnippet:tx,cpuKernelImpl:ij}),MX={kernelName:Xa,backendName:"webgl",kernelFunc:zX};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class nx{constructor(e,t,s){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const o=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=s?`${r}.0`:"1.0";let i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=` + const float exponentMultiplier = ${o}; + + float unaryOpComplex(float real, float expR, float imag, float expI) { + ${i} + } + + float mulMatDFT(int batch, int index) { + float indexRatio = float(index) / float(${r}); + float exponentMultiplierTimesIndexRatio = + exponentMultiplier * indexRatio; + + float result = 0.0; + + for (int i = 0; i < ${r}; i++) { + // x = (-2|2 * PI / N) * index * i; + float x = exponentMultiplierTimesIndexRatio * float(i); + float expR = cos(x); + float expI = sin(x); + float real = getReal(batch, i); + float imag = getImag(batch, i); + + result += + unaryOpComplex(real, expR, imag, expI) / ${a}; + } + + return result; + } + + void main() { + ivec2 coords = getOutputCoords(); + setOutput(mulMatDFT(coords[0], coords[1])); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZS(n,e,t){const s=t.texData.get(n.dataId),r=G(n.shape),o=n.shape[n.shape.length-1],a=r/o,i=se({inputs:{x:n},backend:t,attrs:{shape:[a,o]}}),l=i.shape,u=new nx("real",l,e),c=new nx("imag",l,e),h=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:l},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:l}],d=t.runWebGLProgram(u,h,"float32"),p=t.runWebGLProgram(c,h,"float32"),f=gr({inputs:{real:d,imag:p},backend:t});t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p);const g=se({inputs:{x:f},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(f),g}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BX(n){const{inputs:e,backend:t}=n,{input:s}=e;return ZS(s,!1,t)}const VX={kernelName:cp,backendName:"webgl",kernelFunc:BX};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class WX{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=` + void main() { + // Input can be obtained from uniform value. + setOutput(value); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qi(n){const{backend:e,attrs:t}=n,{shape:s,value:r}=t;let{dtype:o}=t;if(o=o||Kr(r),o==="string"){const a=tt(o,G(s));return a.fill(r),e.makeTensorInfo(s,o,a)}else{const a=new WX(s,r),i=[[r]];return e.runWebGLProgram(a,[],o,i)}}const UX={kernelName:hp,backendName:"webgl",kernelFunc:Qi};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class GX{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + + int coordX = ${t} - x - 1; + float outputValue; + if(coordX >= 0 && coordX < ${t}) { + outputValue = getImage(coords[0], coords[1], coordX, coords[3]); + } else { + outputValue = getImage(coords[0], coords[1], coords[2], coords[3]); + } + setOutput(outputValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HX={kernelName:dp,backendName:"webgl",kernelFunc:({inputs:n,backend:e})=>{const{image:t}=n,s=e,r=new GX(t.shape);return s.runWebGLProgram(r,[t],t.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sx="return floor(x);",jX=Ae({opSnippet:sx,packedOpSnippet:sx,cpuKernelImpl:lj}),qX={kernelName:Ya,backendName:"webgl",kernelFunc:jX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KX=` + float s = sign(a) * sign(b); + int ia = round(a); + int ib = round(b); + if (ib != 0) { + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + return float(idiv(ia, ib, s)); + } else { + return NAN; + } +`,XX=` + ivec4 ia = round(a); + ivec4 ib = round(b); + bvec4 cond = notEqual(ib, ivec4(0)); + ivec4 result = ivec4(0); + vec4 s = sign(a) * sign(b); + + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + if (cond[0]) { + result[0] = idiv(ia[0], ib[0], s[0]); + } + if (cond[1]) { + result[1] = idiv(ia[1], ib[1], s[1]); + } + if (cond[2]) { + result[2] = idiv(ia[2], ib[2], s[2]); + } + if (cond[3]) { + result[3] = idiv(ia[3], ib[3], s[3]); + } + return vec4(result); +`,YX=Ft({opSnippet:KX,packedOpSnippet:XX,dtype:"int32"}),ZX={kernelName:Za,backendName:"webgl",kernelFunc:YX};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class JX{constructor(e){this.variableNames=["A"];const t=Ht(),[s,r]=e;this.outputShape=e,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${s}.0); + + vec4 values = ${t.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + setOutput(floor(value * 255.0 + 0.5)); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class QX{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Ht(),[s,r]=e;this.outputShape=e,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + + vec4 result = vec4(0.); + + for(int row=0; row<=1; row++) { + for(int col=0; col<=1; col++) { + texC = coords[1] + row; + depth = coords[2] + col; + + vec2 uv = (vec2(texC, texR) + halfCR) / + vec2(${r}.0, ${s}.0); + vec4 values = ${t.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + result[row * 2 + col] = floor(value * 255.0 + 0.5); + } + } + + ${t.output} = result; + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const e5={kernelName:Uh,backendName:"webgl",kernelFunc:t5};let uo,Mh=B().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function t5(n){const{inputs:e,backend:t,attrs:s}=n;let{pixels:r}=e;const{numChannels:o}=s,a=typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,[l,u]=a?[r.videoWidth,r.videoHeight]:[r.width,r.height],c=[u,l],h=[u,l,o];if(i||a){const g=B().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(uo==null||g!==Mh)&&(Mh=g,uo=document.createElement("canvas").getContext("2d",{willReadFrequently:Mh})),uo.canvas.width=l,uo.canvas.height=u,uo.drawImage(r,0,0,l,u),r=uo.canvas}const d=t.makeTensorInfo(c,"int32");t.texData.get(d.dataId).usage=gn.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(d.dataId),r);const p=B().getBool("WEBGL_PACK")?new QX(h):new JX(h),f=t.runWebGLProgram(p,[d],"int32");return t.disposeData(d.dataId),f}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n5(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:o,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s,g=Ds(c),m=$t(r.shape,o.shape,l,h,u,d,!1,g);let y;const b=[],w=a!=null,x=i!=null,$=p==="leakyrelu",C=()=>{const A=[r,o],k=(T,S)=>{if(S==="NCHW"&&T.shape.length===1&&T.shape[0]!==1){const _=se({inputs:{x:T},backend:t,attrs:{shape:[T.shape[0],1,1]}});return b.push(_),_}return T};if(w&&A.push(k(a,c)),x&&A.push(k(i,c)),$){const T=t.makeTensorInfo([],"float32",As(f,"float32"));A.push(T),b.push(T)}return A};if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))y=HS({x:r,filter:o,convInfo:m,backend:t,bias:a,activation:p,preluActivationWeights:i,leakyreluAlpha:f});else if(m.strideWidth<=2&&g==="channelsLast"&&B().getBool("WEBGL_EXP_CONV")){const A=p?Aa(p,!0):null,k=new GS(m,w,A,x,$),T=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]],S=C();y=t.runWebGLProgram(k,S,"float32",T)}else if(B().getBool("WEBGL_CONV_IM2COL"))y=jS({x:r,filter:o,convInfo:m,backend:t,bias:a,activation:p,preluActivationWeights:i,leakyreluAlpha:f});else{const A=p?Aa(p,!1):null,k=new US(m,w,A,x,$),T=C();y=t.runWebGLProgram(k,T,"float32")}const E=se({inputs:{x:y},backend:t,attrs:{shape:m.outShape}});return b.push(y),b.forEach(A=>t.disposeIntermediateTensorInfo(A)),E}const s5={kernelName:Fl,backendName:"webgl",kernelFunc:n5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function r5(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:o,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dimRoundingMode:h,activation:d,leakyreluAlpha:p}=s,f=[];let g=c;g==null&&(g=[1,1]),I(Dt(l,g),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${g}'`);const m=$t(r.shape,o.shape,l,g,u,h,!0),y=B().getBool("WEBGL_PACK_DEPTHWISECONV")&&m.strideWidth<=2&&m.outChannels/m.inChannels===1,b=d?Aa(d,y):null,w=[r,o],x=a!=null,$=i!=null,C=d==="leakyrelu";if(x&&w.push(a),$&&w.push(i),C){const T=t.makeTensorInfo([],"float32",As(p,"float32"));w.push(T),f.push(T)}let E;y?E=new XS(m,x,b,$,C):E=new KS(m,x,b,$,C);const A=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]],k=t.runWebGLProgram(E,w,"float32",A);return f.forEach(T=>t.disposeIntermediateTensorInfo(T)),k}const o5={kernelName:Ll,backendName:"webgl",kernelFunc:r5};class a5{constructor(e,t,s,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=s;const o=Pe(s.length);let a=` + int index;`;for(let i=0;i= ${this.paramsShape[i]}; + flattenIndex += index * ${this.strides[i]};`;this.userCode=` + void main() { + ${o} coords = getOutputCoords(); + int flattenIndex = 0; + bool out_of_bounds = false; + + ${a} + + setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1])); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function i5(n){const{inputs:e,backend:t}=n,{params:s,indices:r}=e,o=r.shape,a=o[o.length-1],i=G(s.shape),[l,u,c,h]=Wc(s,r),d=se({inputs:{x:r},backend:t,attrs:{shape:[u,a]}}),p=se({inputs:{x:s},backend:t,attrs:{shape:[G(s.shape)/c,c]}});if(t.shouldExecuteOnCPU([s,r])||s.dtype==="string"){const y=t.readSync(r.dataId),b=t.bufferSync(s),w=uj(y,b,s.dtype,u,a,c,h,s.shape,i);return t.makeTensorInfo(l,s.dtype,w.values)}const f=new a5(a,h,[u,c],s.shape),g=t.runWebGLProgram(f,[p,d],p.dtype),m=se({inputs:{x:g},backend:t,attrs:{shape:l}});return t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(g),m}const l5={kernelName:pp,backendName:"webgl",kernelFunc:i5};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class u5{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const s=Pe(this.rank),r=c5(e);this.userCode=` + void main() { + ${s} resRC = getOutputCoords(); + int index = int(getIndices(resRC.x, resRC.z)); + float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0; + setOutput(inBounds * getA(${r})); + } + `}}function c5(n,e){const t=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r=0,()=>`GatherV2: the index value ${$} is not in [0, ${w-1}]`)}}const u=hm(r,o,l,i),c=G(o.shape),h=[],d=se({inputs:{x:r},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),p=se({inputs:{x:o},backend:t,attrs:{shape:[u.batchSize,c/u.batchSize]}});h.push(d),h.push(p);const f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([r,o])||r.dtype==="string"){const b=t.bufferSync(p),w=t.bufferSync(d),x=cj(w,b,f);return h.forEach($=>t.disposeIntermediateTensorInfo($)),t.makeTensorInfo(u.outputShape,x.dtype,x.values)}const g=new u5(d.shape,f),m=t.runWebGLProgram(g,[d,p],d.dtype);h.push(m);const y=se({inputs:{x:m},backend:t,attrs:{shape:u.outputShape}});return h.forEach(b=>t.disposeIntermediateTensorInfo(b)),y}const h5={kernelName:Ru,backendName:"webgl",kernelFunc:JS};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const d5="return float(a > b);",p5=` + return vec4(greaterThan(a, b)); +`,f5=Ft({opSnippet:d5,packedOpSnippet:p5,cpuKernelImpl:hj,dtype:"bool"}),m5={kernelName:Du,backendName:"webgl",kernelFunc:f5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const g5="return float(a >= b);",y5=` + return vec4(greaterThanEqual(a, b)); +`,b5=Ft({opSnippet:g5,packedOpSnippet:y5,dtype:"bool",cpuKernelImpl:dj}),x5={kernelName:Ja,backendName:"webgl",kernelFunc:b5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w5(n){const{inputs:e,backend:t}=n,{input:s}=e;return ZS(s,!0,t)}const v5={kernelName:fp,backendName:"webgl",kernelFunc:w5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $5="return float(!isnan(x) && !isinf(x));",S5=Ae({opSnippet:$5,dtype:"bool"}),I5={kernelName:ei,backendName:"webgl",kernelFunc:S5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const N5="return float(isinf(x));",C5=Ae({opSnippet:N5,dtype:"bool"}),k5={kernelName:ti,backendName:"webgl",kernelFunc:C5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const T5="return float(isnan(x));",E5=Ae({opSnippet:T5,dtype:"bool"}),A5={kernelName:ni,backendName:"webgl",kernelFunc:E5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const R5="return float(a < b);",D5=` + return vec4(lessThan(a, b)); +`,O5=Ft({opSnippet:R5,packedOpSnippet:D5,cpuKernelImpl:pj,dtype:"bool"}),_5={kernelName:_u,backendName:"webgl",kernelFunc:O5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const F5="return float(a <= b);",L5=` + return vec4(lessThanEqual(a, b)); +`,P5=Ft({opSnippet:F5,packedOpSnippet:L5,cpuKernelImpl:fj,dtype:"bool"}),z5={kernelName:Fu,backendName:"webgl",kernelFunc:P5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function M5(n){const{backend:e,attrs:t}=n,{start:s,stop:r,num:o}=t,a=mj(s,r,o);return e.makeTensorInfo([a.length],"float32",a)}const B5={kernelName:gp,backendName:"webgl",kernelFunc:M5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const V5=Yo+` + return x < 0.0 ? 0./0. : log(x); +`,W5=` + vec4 result = log(x); + bvec4 isNaN = isnan(x); + result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r); + result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g); + result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b); + result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a); + return result; +`,U5=Ae({opSnippet:V5,packedOpSnippet:W5,cpuKernelImpl:gj}),G5={kernelName:si,backendName:"webgl",kernelFunc:U5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const H5=Yo+` + return log(1.0 + x); +`,j5=Ae({opSnippet:H5}),q5={kernelName:ri,backendName:"webgl",kernelFunc:j5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const K5="return float(a >= 1.0 && b >= 1.0);",X5=` + return vec4( + vec4(greaterThanEqual(a, vec4(1.0))) * + vec4(greaterThanEqual(b, vec4(1.0)))); +`,Y5=Ft({opSnippet:K5,packedOpSnippet:X5,dtype:"bool"}),Z5={kernelName:Lu,backendName:"webgl",kernelFunc:Y5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const J5="return float(!(x >= 1.0));",Q5=Ae({opSnippet:J5}),e8={kernelName:Pu,backendName:"webgl",kernelFunc:Q5};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const t8="return float(a >= 1.0 || b >= 1.0);",n8=` + return min( + vec4(greaterThanEqual(a, vec4(1.0))) + + vec4(greaterThanEqual(b, vec4(1.0))), + vec4(1.0)); +`,s8=Ft({opSnippet:t8,packedOpSnippet:n8,dtype:"bool"}),r8={kernelName:zu,backendName:"webgl",kernelFunc:s8};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class o8{constructor(e,t,s,r,o){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;this.outputShape=e;let l;const u=`float(${s}) + float(${r}) * sum`;o===.5?l=`inversesqrt(${u})`:o===1?l=`1.0/(${u})`:l=`exp(log(${u}) * float(-${o}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + int d = coords[3]; + float x = getX(b, r, c, d); + float sum = 0.0; + for (int j = -${a}; j <= ${a}; j++) { + int idx = d + j; + if (idx >= 0 && idx <= ${i}) { + float z = getX(b, r, c, idx); + sum += z * z; + } + } + float val = x * ${l}; + setOutput(val); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class a8{constructor(e,t,s,r,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=t,i=e[3]-1;this.outputShape=e;let l;const u=`float(${s}) + float(${r}) * sum`;o===.5?l=`inversesqrt(${u})`:o===1?l=`1.0/(${u})`:l=`exp(log(${u}) * float(-${o}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords.x; + int r = coords.y; + int c = coords.z; + int d = coords.w; + + bool hasNextCol = d < ${this.outputShape[3]}; + bool hasNextRow = c < ${this.outputShape[2]}; + + vec4 sum = vec4(0.); + vec4 xFragAtOutputCoords = getX(b, r, c, d); + + vec4 xAtOutputCoords = vec4( + getChannel(xFragAtOutputCoords, vec2(c, d)), + hasNextCol ? + getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0, + hasNextRow ? + getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0, + (hasNextRow && hasNextCol) ? + getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0 + ); + + int firstChannel = d - ${a}; + vec2 cache = vec2(0.); + if(firstChannel >= 0){ + vec4 firstChannelFrag = getX(b, r, c, firstChannel); + cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel)); + if(hasNextRow){ + cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel)); + } + } + + ivec2 depth = ivec2(d, d + 1); + for (int j = - ${a}; j <= ${a}; j++) { + ivec2 idx = depth + j; + bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); + bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i})); + + bool depthInRange = aboveLowerBound.x && belowUpperBound.x; + bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y; + + if(depthInRange || depthPlusOneInRange){ + vec4 z = vec4(0.); + vec4 xFragAtCurrentDepth; + z.xz = cache.xy; + if(depthPlusOneInRange && hasNextCol){ + xFragAtCurrentDepth = idx.y != d ? + getX(b, r, c, idx.y) : xFragAtOutputCoords; + z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y)); + if(hasNextRow){ + z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y)); + } + } + cache.xy = z.yw; + sum += z * z; + } + } + vec4 result = xAtOutputCoords * ${l}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const i8=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{depthRadius:o,bias:a,alpha:i,beta:l}=s,u=B().getBool("WEBGL_PACK_NORMALIZATION")?new a8(r.shape,o,a,i,l):new o8(r.shape,o,a,i,l);return t.runWebGLProgram(u,[r],r.dtype)},l8={kernelName:Mu,backendName:"webgl",kernelFunc:i8};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class u8{constructor(e,t,s,r,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=s,this.alpha=r,this.beta=o,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + + float result = 0.0; + for (int d = 0; d < ${this.depth}; ++d) { + int depthBegin = int(max(0.0, float(d - ${t}))); + int depthEnd = int(min(float(${this.depth}), + float(d + ${t} + 1))); + + const int MIN_DEPTH_BEGIN = 0; + const int MAX_DEPTH_END = ${this.depth}; + + float norm = 0.0; + for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) { + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd) { + norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); + } + else { + break; + } + } + + norm = float(${r}) * norm + float(${s}); + + for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){ + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd){ + float dyi = -2.0 * float(${r}) + * float(${o}) + * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) + / norm; + if (k == d) { + dyi += pow(norm, -1.0 * ${o}); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } + else { + break; + } + } + } + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const c8=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r,y:o,dy:a}=e,{depthRadius:i,bias:l,alpha:u,beta:c}=s,h=new u8(r.shape,i,l,u,c);return t.runWebGLProgram(h,[r,o,a],r.dtype)},h8={kernelName:yp,backendName:"webgl",kernelFunc:c8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d8(n,e,t,s){const r=G(e),a=G(n.shape)/r,i=se({inputs:{x:n},attrs:{shape:[a,r]},backend:s}),l=ao(i,n.dtype,"max",s),u=se({inputs:{x:l},attrs:{shape:t},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),u}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QS(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{reductionIndices:o,keepDims:a}=s,i=r.shape.length,l=Se(o,r.shape);let u=l;const c=Je(u,i),h=c!=null,d=t.shouldExecuteOnCPU([r]);let p=r;if(h){if(d){const w=t.texData.get(p.dataId).values,x=new Array(i);for(let E=0;E`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);const c=Dn(r.shape,o,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&Ce(c.inShape,c.outShape))return cn({inputs:{x:r},backend:t});const h=new Ra(c,"max",!1);return t.runWebGLProgram(h,[r],r.dtype)}const x8={kernelName:Vu,backendName:"webgl",kernelFunc:b8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w8(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:o,strides:a,pad:i,dataFormat:l,dimRoundingMode:u}=s,c=[1,1,1],h=Rs(r.shape,o,a,c,i,u,l),d=new my(h,"max",!1);return t.runWebGLProgram(d,[r],r.dtype)}const v8={kernelName:Wu,backendName:"webgl",kernelFunc:w8};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $8{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,s=e.strideWidth,r=e.dilationHeight,o=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=o-1-e.padInfo.top,l=a-1-e.padInfo.left,u=o*a-1;this.userCode=` + const ivec2 pads = ivec2(${i}, ${l}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${o}; + wR += ${r}) { + float dyR = float(dyRCorner + wR) / ${t}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${a}; wC++) { + float dyC = float(dyCCorner + wC) / ${s}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = wR * ${a} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + setOutput(dotProd); + } + `}}class S8{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,s=e.strideHeight,r=e.strideWidth,o=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,l=e.effectiveFilterDepth,u=e.effectiveFilterHeight,c=e.effectiveFilterWidth,h=l-1-e.padInfo.front,d=u-1-e.padInfo.top,p=c-1-e.padInfo.left,f=l*u*c-1;this.userCode=` + const ivec3 pads = ivec3(${h}, ${d}, ${p}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${l}; + wD += ${o}) { + float dyD = float(dyDCorner + wD) / ${t}.0; + + if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${u}; + wR += ${a}) { + float dyR = float(dyRCorner + wR) / ${s}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${c}; + wC += ${i}) { + float dyC = float(dyCCorner + wC) / ${r}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + int maxPosValue = ${f} - + int(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = + wD * ${u} * ${c} + + wR * ${c} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function I8(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o}=e,a=o,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=s,h=[1,1,1],d=Rs(a.shape,i,l,h,u,c),p=new my(d,"max",!0),f=t.runWebGLProgram(p,[a],a.dtype),g=new S8(d),m=t.runWebGLProgram(g,[r,f],a.dtype);return t.disposeIntermediateTensorInfo(f),m}const N8={kernelName:xp,backendName:"webgl",kernelFunc:I8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function C8(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:o,output:a}=e,i=o;Go([o,a],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,d=Dn(i.shape,l,u,1,c,h),p=!0,f=new Ra(d,"max",p),g=t.runWebGLProgram(f,[i],i.dtype),m=new $8(d),y=t.runWebGLProgram(m,[r,g],i.dtype);return t.disposeIntermediateTensorInfo(g),y}const k8={kernelName:bp,backendName:"webgl",kernelFunc:C8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function T8(n,e,t,s){let r=new Ra(t,"max",!1);const o=s.runWebGLProgram(r,[n],"float32");r=new Ra(t,"max",!0,!0,e);const a=s.runWebGLProgram(r,[n],"float32");return[o,a]}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const E8={kernelName:wp,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{filterSize:r,strides:o,pad:a,includeBatchInIndex:i}=e,l=t;I(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const u=[1,1];I(Dt(o,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);const c=Dn(s.shape,r,o,u,a),[h,d]=T8(s,i,c,l);return[h,d]}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A8(n,e,t,s){const r=G(e),a=G(n.shape)/r,i=se({inputs:{x:n},attrs:{shape:[a,r]},backend:s}),l=ao(i,"float32","mean",s),u=se({inputs:{x:l},attrs:{shape:t},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),u}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const R8={kernelName:Uu,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{keepDims:r,axis:o}=e,a=t,i=s.shape.length,l=Se(o,s.shape);let u=l;const c=Je(u,i),h=c!=null,d=a.shouldExecuteOnCPU([s]),p=[];let f=s;if(h){if(d){const x=a.texData.get(f.dataId).values,$=new Array(i);for(let A=0;A<$.length;A++)$[A]=s.shape[c[A]];const C=dy(x,s.shape,s.dtype,c,$);f=a.makeTensorInfo($,s.dtype);const E=a.texData.get(f.dataId);E.values=C}else f=yh(s,c,a);p.push(f),u=st(u.length,i)}Ot("sum",u,i);const[g,m]=St(f.shape,u);let y=g;r&&(y=nt(g,l));const b=A8(f,m,y,a);for(const w of p)a.disposeIntermediateTensorInfo(w);return b}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function D8(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s,i=r.shape.length,l=Se(o,r.shape);let u=l;const c=Je(u,i);let h=r;c!=null&&(h=Ut({inputs:{x:r},backend:t,attrs:{perm:c}}),u=st(u.length,r.shape.length)),Ot("min",u,i);const[d,p]=St(h.shape,u),f=G(p),g=se({inputs:{x:h},backend:t,attrs:{shape:[-1,f]}}),m=ao(g,g.dtype,"min",t);let y;if(a){const b=nt(d,l);y=se({inputs:{x:m},backend:t,attrs:{shape:b}})}else y=se({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(m),c!=null&&t.disposeIntermediateTensorInfo(h),y}const O8={kernelName:Gu,backendName:"webgl",kernelFunc:D8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _8=py+` + return min(a, b); +`,F8=` + vec4 result = vec4(min(a, b)); + bvec4 isNaNA = isnan(a); + bvec4 isNaNB = isnan(b); + bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w); + `+oo+` + return result; +`,L8=Ft({opSnippet:_8,packedOpSnippet:F8,cpuKernelImpl:xj}),P8={kernelName:ai,backendName:"webgl",kernelFunc:L8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class z8{constructor(e,t,s){this.variableNames=["x"],this.outputShape=t.map((c,h)=>c[0]+e[h]+c[1]);const r=e.length,o=Pe(r),a=t.map(c=>c[0]).join(","),i=t.map((c,h)=>c[0]+e[h]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u=s==="reflect"?0:1;if(r===1){this.userCode=` + int start = ${a}; + int end = ${i}; + + void main() { + int outC = getOutputCoords(); + if (outC < start) { + outC = start * 2 - outC - ${u}; + } else if(outC >= end) { + outC = (end - 1) * 2 - outC + ${u}; + } + setOutput(getX(outC - start)); + } + `;return}this.userCode=` + ${o} start = ${o}(${a}); + ${o} end = ${o}(${i}); + + void main() { + ${o} outC = getOutputCoords(); + for (int i = 0; i < ${r}; i++) { + if (outC[i] < start[i]) { + outC[i] = start[i] * 2 - outC[i] - ${u}; + } else if(outC[i] >= end[i]) { + outC[i] = (end[i] - 1) * 2 - outC[i] + ${u}; + } + } + ${o} coords = outC - start; + setOutput(getX(${l})); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class M8{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((f,g)=>f[0]+e[g]+f[1]);const r=e.length,o=Pe(r),a=t.map(f=>f[0]).join(","),i=t.map((f,g)=>f[0]+e[g]).join(","),l=Wt("rc",r),u=Wt("source",r),c=`${l[r-1]} < ${this.outputShape[r-1]}`,h=r===1?"source":`vec2(${u.slice(-2).join()})`,d=s==="reflect"?0:1;let p="";if(r===1){const f=` + ${o} source = rc; + if (source < start) { + source = start * 2 - source - ${d}; + } else if (source >= end) { + source = (end - 1) * 2 - source + ${d}; + } + source -= start; + `;p=` + ${o} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${u.join()}), ${h}); + ${l[r-1]} += 1; + if(${c}) { + ${f} + result[1] = getChannel(getX(${u.join()}), ${h}); + } + `}else{const f=` + ${o} source = rc; + ${o} lt = ${o}(lessThan(source, start)); + ${o} gte = ${o}(greaterThanEqual(source, end)); + ${o} orig = 1 - (lt + gte); + source = orig * source + + lt * (start * 2 - source - ${d}) + + gte * ((end - 1) * 2 - source + ${d}); + source -= start; + `;p=` + ${o} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${u.join()}), ${h}); + ${l[r-1]} += 1; + if(${c}) { + ${f} + result[1] = getChannel(getX(${u.join()}), ${h}); + } + rc = outputLoc; + ${l[r-2]} += 1; + if(${l[r-2]} < ${this.outputShape[r-2]}) { + ${f} + result[2] = getChannel(getX(${u.join()}), ${h}); + ${l[r-1]} += 1; + if(${c}) { + ${f} + result[3] = getChannel(getX(${u.join()}), ${h}); + } + } + `}this.userCode=` + const ${o} start = ${o}(${a}); + const ${o} end = ${o}(${i}); + + void main() { + ${o} outputLoc = getOutputCoords(); + vec4 result = vec4(0.); + ${p} + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const B8=({inputs:n,backend:e,attrs:t})=>{const{x:s}=n,{paddings:r,mode:o}=t,a=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new M8(s.shape,r,o):new z8(s.shape,r,o);return e.runWebGLProgram(a,[s],s.dtype)},V8={kernelName:Hu,backendName:"webgl",kernelFunc:B8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const W8=`if (b == 0.0) return NAN; + return mod(a, b);`,U8=` + vec4 result = mod(a, b); + bvec4 isNaN = equal(b, vec4(0.0)); + `+oo+` + return result; +`,G8=Ft({opSnippet:W8,packedOpSnippet:U8}),H8={kernelName:ii,backendName:"webgl",kernelFunc:G8};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class j8{constructor(e,t,s){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,s],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + + float r = random(seed); + float cdf = 0.0; + + for (int i = 0; i < ${t-1}; i++) { + cdf += getProbs(batch, i); + + if (r < cdf) { + setOutput(float(i)); + return; + } + } + + // If no other event happened, last event happened. + setOutput(float(${t-1})); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const q8=` +if (a == b) { + return 1.0; +}; +return a / b;`,K8=` + // vec4 one = vec4(equal(a, b)); + // return one + (vec4(1.0) - one) * a / b; + vec4 result = a / b; + if(a.x == b.x) { + result.x = 1.; + } + if(a.y == b.y) { + result.y = 1.; + } + if(a.z == b.z) { + result.z = 1.; + } + if(a.w == b.w) { + result.w = 1.; + } + + return result; +`,eI=Ft({opSnippet:q8,packedOpSnippet:K8,checkOutOfBounds:!0}),X8={kernelName:Ha,backendName:"webgl",kernelFunc:eI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rx="return a - b;",tI=Ft({opSnippet:rx,packedOpSnippet:rx,supportsComplex:!0,cpuKernelImpl:Bj}),Y8={kernelName:Si,backendName:"webgl",kernelFunc:tI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nI(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{dim:o}=s,a=Se([o],r.shape),i=QS({inputs:{x:r},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),l=nt(i.shape,a),u=se({inputs:{x:i},backend:t,attrs:{shape:l}}),c=tI({inputs:{a:r,b:u},backend:t}),h=YS({inputs:{x:c},backend:t}),d=bh({inputs:{x:h},backend:t,attrs:{axis:a,keepDims:!1}}),p=se({inputs:{x:d},backend:t,attrs:{shape:l}}),f=eI({inputs:{a:h,b:p},backend:t});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p),f}const Z8={kernelName:uc,backendName:"webgl",kernelFunc:nI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function J8(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{numSamples:o,seed:a,normalized:i}=s,l=i?r:nI({inputs:{logits:r},backend:t,attrs:{dim:r.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new j8(u,c,o),d=[[a]],p=t.runWebGLProgram(h,[l],"int32",d);return i||t.disposeIntermediateTensorInfo(l),p}const Q8={kernelName:vp,backendName:"webgl",kernelFunc:J8};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eY=_n+` + return -x; +`,tY=` + vec4 result = -x; + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`;function nY(n){const{inputs:e,backend:t}=n,{x:s}=e;if(t.shouldExecuteOnCPU([s])){const o=t.texData.get(s.dataId),[a,i]=vj(o.values,s.shape,s.dtype);return t.makeTensorInfo(i,s.dtype,a)}let r;return B().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Hs(s.shape,tY):r=new ts(s.shape,eY),t.runWebGLProgram(r,[s],s.dtype)}const sY={kernelName:ju,backendName:"webgl",kernelFunc:nY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rY=Mc;function oY(n){fn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:o}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=s,u=t.readSync(r.dataId),c=t.readSync(o.dataId),{selectedIndices:h}=rY(u,c,a,i,l);return t.makeTensorInfo([h.length],"int32",new Int32Array(h))}const aY={kernelName:$p,backendName:"webgl",kernelFunc:oY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iY=Bc;function lY(n){fn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:o}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=s,c=t.readSync(r.dataId),h=t.readSync(o.dataId),{selectedIndices:d,validOutputs:p}=iY(c,h,a,i,l,u);return[t.makeTensorInfo([d.length],"int32",new Int32Array(d)),t.makeTensorInfo([],"int32",new Int32Array([p]))]}const uY={kernelName:Sp,backendName:"webgl",kernelFunc:lY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cY=Vc;function hY(n){fn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:o}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=s,c=t.readSync(r.dataId),h=t.readSync(o.dataId),d=a,p=i,f=l,g=u,{selectedIndices:m,selectedScores:y}=cY(c,h,d,p,f,g);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([y.length],"float32",new Float32Array(y))]}const dY={kernelName:Ip,backendName:"webgl",kernelFunc:hY};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class pY{constructor(e,t,s,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int index = round(getIndices(coords.x)); + setOutput(mix(float(${r}), float(${s}), + float(index == coords.y))); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fY=n=>{const{inputs:e,backend:t,attrs:s}=n,{indices:r}=e,{dtype:o,depth:a,onValue:i,offValue:l}=s,u=G(r.shape),c=new pY(u,a,i,l),h=se({inputs:{x:r},backend:t,attrs:{shape:[u]}}),d=t.runWebGLProgram(c,[h],o);t.disposeIntermediateTensorInfo(h);const p=[...r.shape,a],f=se({inputs:{x:d},backend:t,attrs:{shape:p}});return t.disposeIntermediateTensorInfo(d),f},mY={kernelName:Xu,backendName:"webgl",kernelFunc:fY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lu(n){const{inputs:e,backend:t}=n,{x:s}=e;if(s.dtype==="complex64"){const r=Ji({inputs:{input:s},backend:t}),o=lu({inputs:{x:r},backend:t}),a=xh({inputs:{input:s},backend:t}),i=lu({inputs:{x:a},backend:t}),l=gr({inputs:{real:o,imag:i},backend:t});return t.disposeIntermediateTensorInfo(r),t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return Qi({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:t})}const gY={kernelName:pc,backendName:"webgl",kernelFunc:lu};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sI(n){const{inputs:e,backend:t}=n,{x:s}=e;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){const r=Ji({inputs:{input:s},backend:t}),o=sI({inputs:{x:r},backend:t}),a=xh({inputs:{input:s},backend:t}),i=lu({inputs:{x:a},backend:t}),l=gr({inputs:{real:o,imag:i},backend:t});return t.disposeIntermediateTensorInfo(r),t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return Qi({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:t})}const yY={kernelName:Ku,backendName:"webgl",kernelFunc:sI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bY(n){const{inputs:e,backend:t,attrs:s}=n,{axis:r}=s;if(e.length===1)return Pd({inputs:{input:e[0]},backend:t,attrs:{dim:r}});const o=e[0].shape,a=e[0].dtype;e.forEach(c=>{Rt(o,c.shape,"All tensors passed to stack must have matching shapes"),I(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const i=[],l=e.map(c=>{const h=Pd({inputs:{input:c},backend:t,attrs:{dim:r}});return i.push(h),h}),u=WS({inputs:l,backend:t,attrs:{axis:r}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}const xY={kernelName:Yu,backendName:"webgl",kernelFunc:bY};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class wY{constructor(e,t,s){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((u,c)=>u[0]+e[c]+u[1]);const r=e.length,o=Pe(r),a=t.map(u=>u[0]).join(","),i=t.map((u,c)=>u[0]+e[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=` + int start = ${a}; + int end = ${i}; + + void main() { + int outC = getOutputCoords(); + if (outC < start || outC >= end) { + setOutput(value); + } else { + setOutput(getX(outC - start)); + } + } + `;return}this.userCode=` + ${o} start = ${o}(${a}); + ${o} end = ${o}(${i}); + + void main() { + ${o} outC = getOutputCoords(); + if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { + setOutput(value); + } else { + ${o} coords = outC - start; + setOutput(getX(${l})); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vY{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((g,m)=>g[0]+e[m]+g[1]);const r=e.length,o=Pe(r),a=t.map(g=>g[0]).join(","),i=t.map((g,m)=>g[0]+e[m]).join(","),l=Wt("rc",r),u=Wt("source",r),c=`${l[r-1]} < ${this.outputShape[r-1]}`,h=r===1?"source":`vec2(${u.slice(-2).join()})`,d=[`${o} rc = outputLoc;`,`${l[r-1]} += 1; + if(${c}) { + `,r===1?"":`} + rc = outputLoc; + ${l[r-2]} += 1; + if(${l[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${l[r-1]} += 1; + if(${c}) {`],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let f="";for(let g=0,m=r===1?2:4;g{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{paddings:o,constantValue:a}=s;if(G(r.shape)===0){const u=o.map((c,h)=>c[0]+r.shape[h]+c[1]);return Qi({backend:t,attrs:{shape:u,value:a,dtype:r.dtype}})}const i=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new vY(r.shape,o,a):new wY(r.shape,o,a),l=[[a]];return t.runWebGLProgram(i,[r],r.dtype,l)},$Y={kernelName:Zu,backendName:"webgl",kernelFunc:rI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SY=` + if(a < 0.0 && floor(b) < b){ + return NAN; + } + if (b == 0.0) { + return 1.0; + } + return (round(mod(b, 2.0)) != 1) ? + pow(abs(a), b) : sign(a) * pow(abs(a), b); +`,IY=` + // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise. + vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1))); + vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); + vec4 result = multiplier * pow(abs(a), b); + + // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS + bvec4 isExpZero = equal(b, vec4(0.0)); + result.r = isExpZero.r ? 1.0 : result.r; + result.g = isExpZero.g ? 1.0 : result.g; + result.b = isExpZero.b ? 1.0 : result.b; + result.a = isExpZero.a ? 1.0 : result.a; + + bvec4 isNaN1 = lessThan(a, vec4(0.0)); + bvec4 isNaN2 = lessThan(floor(b), b); + bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w); + `+oo+` + return result; +`,NY=Ft({opSnippet:SY,packedOpSnippet:IY}),CY={kernelName:ui,backendName:"webgl",kernelFunc:NY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kY(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:o,keepDims:a}=s,i=r.shape.length,l=[],u=Se(o,r.shape);let c=u;const h=Je(c,i);let d=r;h!=null&&(d=Ut({inputs:{x:r},backend:t,attrs:{perm:h}}),c=st(c.length,i),l.push(d)),Ot("prod",c,i);let p;if(t.shouldExecuteOnCPU([d])){const f=t.texData.get(d.dataId).values,{outVals:g,outShape:m,outDtype:y}=Sj(d.shape,d.dtype,f,c);p=t.makeTensorInfo(m,y,g)}else{const[f,g]=St(d.shape,c),m=G(g),y=se({inputs:{x:d},backend:t,attrs:{shape:[-1,m]}}),b=Zp(r.dtype),w=ao(y,b,"prod",t);p=se({inputs:{x:w},backend:t,attrs:{shape:f}}),l.push(y),l.push(w)}if(a){l.push(p);const f=nt(p.shape,u);p=se({inputs:{x:p},backend:t,attrs:{shape:f}})}return l.forEach(f=>t.disposeIntermediateTensorInfo(f)),p}const TY={kernelName:Qu,backendName:"webgl",kernelFunc:kY};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EY(n){const{inputs:e,backend:t,attrs:s}=n,{paramsNestedSplits:r,paramsDenseValues:o,indices:a}=e,{outputRaggedRank:i}=s,l=r.map(y=>t.readSync(y.dataId)),u=r.map(y=>y.shape),c=t.readSync(o.dataId),h=t.readSync(a.dataId),[d,p,f]=Ij(l,u,c,o.shape,o.dtype,h,a.shape,i),g=d.map(y=>t.makeTensorInfo([y.length],"int32",y)),m=t.makeTensorInfo(f,o.dtype,p);return g.concat([m])}const AY={kernelName:Np,backendName:"webgl",kernelFunc:EY};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RY(n){const{inputs:e,backend:t}=n,{starts:s,limits:r,deltas:o}=e,a=t.readSync(s.dataId),i=t.readSync(r.dataId),l=t.readSync(o.dataId),[u,c]=Nj(a,s.shape,s.dtype,i,r.shape,l,o.shape),h=t.makeTensorInfo([u.length],"int32",u),d=t.makeTensorInfo([c.length],s.dtype,c);return[h,d]}const DY={kernelName:Cp,backendName:"webgl",kernelFunc:RY};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OY(n){const{inputs:e,backend:t,attrs:s}=n,{shape:r,values:o,defaultValue:a,rowPartitionTensors:i}=e,{rowPartitionTypes:l}=s,u=t.readSync(r.dataId),c=t.readSync(o.dataId),h=t.readSync(a.dataId),d=i.map(m=>t.readSync(m.dataId)),p=i.map(m=>m.shape),[f,g]=Cj(u,r.shape,c,o.shape,o.dtype,h,a.shape,d,p,l);return t.makeTensorInfo(f,o.dtype,g)}const _Y={kernelName:kp,backendName:"webgl",kernelFunc:OY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oI=n=>{const{backend:e,attrs:t}=n,{start:s,stop:r,step:o,dtype:a}=t,i=kj(s,r,o,a);return e.makeTensorInfo([i.length],a,i)},FY={kernelName:Tp,backendName:"webgl",kernelFunc:oI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LY="return 1.0 / x;",PY=Ae({opSnippet:LY}),zY={kernelName:ci,backendName:"webgl",kernelFunc:PY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MY=_n+` + return (x < 0.0) ? 0.0 : x; +`,BY=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,VY=Ae({opSnippet:MY,packedOpSnippet:BY}),WY={kernelName:hi,backendName:"webgl",kernelFunc:VY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UY=_n+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,GY=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,HY=Ae({opSnippet:UY,packedOpSnippet:GY}),jY={kernelName:di,backendName:"webgl",kernelFunc:HY};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qY{constructor(e,t,s,r,o){this.variableNames=["A"],this.outputShape=[];const[a,i,l,u]=e;this.outputShape=[a,t,s,u];const c=[r&&t>1?i-1:i,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s];let d;o?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${c[0]/h[0]}, + ${c[1]/h[1]}); + const vec2 inputShapeRC = vec2(${i}.0, ${l}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${d}; + + // Compute the four integer indices. + ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0))); + ivec2 sourceCeilRC = ivec2( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d); + float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d); + float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d); + float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d); + + vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC); + + float top = topLeft + (topRight - topLeft) * fracRC.y; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; + float newValue = top + (bottom - top) * fracRC.x; + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class KY{constructor(e,t,s,r,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,l,u]=e;this.outputShape=[a,t,s,u];const c=[r&&t>1?i-1:i,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s];let d;o?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${c[0]/h[0]}, + ${c[1]/h[1]}, + ${c[1]/h[1]}); + const vec3 inputShapeRC = vec3(${i}.0, ${l}.0, + ${l}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${d}; + + // Compute the four integer indices. + ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0))); + ivec3 sourceCeilRC = ivec3( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${u-1}; + bool hasNextRow = coords.z < ${s-1}; + + // In parallel, construct four corners for all four components in + // packed 2x2 cell. + vec4 topLeft = vec4( + getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 bottomLeft = vec4( + getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 topRight = vec4( + getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec4 bottomRight = vec4( + getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC); + + vec4 top = mix(topLeft, topRight, fracRC.yyzz); + vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz); + vec4 newValue = mix(top, bottom, fracRC.x); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XY(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:o,halfPixelCenters:a,size:i}=s,[l,u]=i,c=B().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new KY(r.shape,l,u,o,a):new qY(r.shape,l,u,o,a);return t.runWebGLProgram(c,[r],"float32")}const YY={kernelName:nc,backendName:"webgl",kernelFunc:XY};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ZY{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,o]=t,[,a,i]=e,l=[s&&a>1?r-1:r,s&&i>1?o-1:o],u=[s&&a>1?a-1:a,s&&i>1?i-1:i],c=l[0]/u[0],h=l[1]/u[1],d=1/c,p=1/h,f=Math.ceil(d)*2+2,g=Math.ceil(p)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${c}); + const float widthScale = float(${h}); + + const float invHeightScale = float(${d}); + const float invWidthScale = float(${p}); + + const int winHeight = int(${f}); + const int winWidth = int(${g}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(startRLerp - float(winHeight / 2)); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(startCLerp - float(winWidth / 2)); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${a}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${i}) { + continue; + } + + float dxR = float(dyR) * heightScale; + int topDxRIndex = int(floor(dxR)); + int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0)); + float dxRLerp = dxR - float(topDxRIndex); + float inverseDxRLerp = 1.0 - dxRLerp; + + float dxC = float(dyC) * widthScale; + int leftDxCIndex = int(floor(dxC)); + int rightDxCIndex = int(min(ceil(dxC), ${o-1}.0)); + float dxCLerp = dxC - float(leftDxCIndex); + float inverseDxCLerp = 1.0 - dxCLerp; + + if (r == topDxRIndex && c == leftDxCIndex) { + // topLeft + accumulator += + getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; + } + + if (r == topDxRIndex && c == rightDxCIndex) { + // topRight + accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; + } + + if (r == bottomDxRIndex && c == leftDxCIndex) { + // bottomLeft + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; + } + + if (r == bottomDxRIndex && c == rightDxCIndex) { + // bottomRight + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JY(n){const{inputs:e,backend:t,attrs:s}=n,{images:r,dy:o}=e,{alignCorners:a}=s,i=new ZY(o.shape,r.shape,a);return t.runWebGLProgram(i,[o],o.dtype)}const QY={kernelName:Rp,backendName:"webgl",kernelFunc:JY};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class e7{constructor(e,t,s,r,o){this.variableNames=["A"],this.outputShape=[];const[a,i,l,u]=e;this.outputShape=[a,t,s,u];const c=[r&&t>1?i-1:i,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s],d=r?"0.5":"0.0";let p;o?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${c[0]/h[0]}, + ${c[1]/h[1]}); + const vec2 inputShapeRC = vec2(${i}.0, ${l}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${p}; + + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestRC = ivec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d}))); + float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class t7{constructor(e,t,s,r,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,l,u]=e;this.outputShape=[a,t,s,u];const c=[r&&t>1?i-1:i,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s],d=r?"0.5":"0.0";let p;o?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${c[0]/h[0]}, + ${c[1]/h[1]}, + ${c[1]/h[1]}); + const vec3 inputShapeRC = vec3(${i}.0, ${l}.0, + ${l}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${p}; + + // Compute the coordinators of nearest neighbor point. + ivec3 sourceNearestRC = ivec3( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d}))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${u-1}; + bool hasNextRow = coords.z < ${s-1}; + + vec4 newValue = vec4( + getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d), + hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n7(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:o,halfPixelCenters:a,size:i}=s,[l,u]=i,c=B().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new t7(r.shape,l,u,o,a):new e7(r.shape,l,u,o,a);return t.runWebGLProgram(c,[r],r.dtype)}const s7={kernelName:tc,backendName:"webgl",kernelFunc:n7};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class r7{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,o]=t,[,a,i]=e,l=[s&&a>1?r-1:r,s&&i>1?o-1:o],u=[s&&a>1?a-1:a,s&&i>1?i-1:i],c=l[0]/u[0],h=l[1]/u[1],d=1/c,p=1/h,f=Math.ceil(d)*2+2,g=Math.ceil(p)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${c}); + const float widthScale = float(${h}); + + const float invHeightScale = float(${d}); + const float invWidthScale = float(${p}); + + const int winHeight = int(${f}); + const int winWidth = int(${g}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(floor(startRLerp - float(winHeight / 2))); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(floor(startCLerp - float(winWidth / 2))); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${a}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${i}) { + continue; + } + + float sourceFracRow = + float(${l[0]}) * + (float(dyR) / float(${u[0]})); + + float sourceFracCol = + float(${l[1]}) * + (float(dyC) / float(${u[1]})); + + int sourceNearestRow = int(min( + float(int(${r}) - 1), + ${s} ? float(round(sourceFracRow)) : + float(floor(sourceFracRow)))); + + int sourceNearestCol = int(min( + float(int(${o}) - 1), + ${s} ? float(round(sourceFracCol)) : + float(floor(sourceFracCol)))); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function o7(n){const{inputs:e,backend:t,attrs:s}=n,{images:r,dy:o}=e,{alignCorners:a}=s,i=new r7(o.shape,r.shape,a);return t.runWebGLProgram(i,[o],o.dtype)}const a7={kernelName:Ap,backendName:"webgl",kernelFunc:o7};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class i7{constructor(e,t){this.variableNames=["x"];const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=e,s===1){this.userCode=` + void main() { + int coord = getOutputCoords(); + setOutput(getX(${e[0]} - coord - 1)); + } + `;return}const r=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,o=e.map((i,l)=>r(l)).join(","),a=Pe(s);this.userCode=` + void main() { + ${a} coords = getOutputCoords(); + setOutput(getX(${o})); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class l7{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=e;const r=Wt("rc",s),o=`${r[s-1]} + 1 < ${this.outputShape[s-1]}`,a=`${r[s-2]} + 1 < ${this.outputShape[s-2]}`,i=Pe(s);s===1?this.userCode=` + void main(){ + int rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = getChannel(getX(${e[0]} - rc - 1), + ${e[0]} - rc - 1); + if(${o}){ + result.g = getChannel(getX(${e[0]} - (rc + 1) - 1), + ${e[0]} - (rc + 1) - 1); + } + setOutput(result); + } + `:this.userCode=` + void main() { + ${i} rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = ${l(r.slice())}; + if(${o}){ + result.g = ${u(r.slice())}; + } + if(${a}) { + result.b = ${c(r.slice())}; + if(${o}) { + result.a = ${h(r.slice())}; + } + } + setOutput(result); + } + `;function l(f){return d(f)}function u(f){return f[s-1]="("+f[s-1]+" + 1)",d(f)}function c(f){return f[s-2]="("+f[s-2]+" + 1)",d(f)}function h(f){return f[s-1]="("+f[s-1]+" + 1)",f[s-2]="("+f[s-2]+" + 1)",d(f)}function d(f){const g=e.map((b,w)=>p(w,f)),m=g.join(","),y=g.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${y}))`}function p(f,g){return t.indexOf(f)!==-1&&e[f]!==1?`${e[f]} - ${g[f]} - 1`:`${g[f]}`}}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function u7(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dims:o}=s,a=r.shape.length,i=Se(o,r.shape);if(a===0)return cn({inputs:{x:r},backend:t});const l=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new l7(r.shape,i):new i7(r.shape,i);return t.runWebGLProgram(l,[r],r.dtype)}const c7={kernelName:sc,backendName:"webgl",kernelFunc:u7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class h7{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const s=e[1],r=e[2];this.outputShape=e;let o="";typeof t=="number"?o=`float outputValue = ${t.toFixed(2)};`:o=` + vec3 fill = vec3(${t.join(",")}); + float outputValue = fill[coords[3]];`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + int y = coords[1]; + float coordXFloat = (float(x) - params[0]) * params[3] - + (float(y) - params[1]) * params[2]; + float coordYFloat = (float(x) - params[0]) * params[2] + + (float(y) - params[1]) * params[3]; + int coordX = int(round(coordXFloat + params[0])); + int coordY = int(round(coordYFloat + params[1])); + ${o} + if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${s}) { + outputValue = getImage(coords[0], coordY, coordX, coords[3]); + } + setOutput(outputValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const d7={kernelName:Kp,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:s}=n,{radians:r,fillValue:o,center:a}=e,i=t,l=new h7(s.shape,o),[u,c]=Xf(a,s.shape[1],s.shape[2]),h=[[u,c,Math.sin(r),Math.cos(r)]];return i.runWebGLProgram(l,[s],s.dtype,h)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const p7=` + // OpenGL ES does not support round function. + // The algorithm is based on banker's rounding. + float base = floor(x); + if ((x - base) < 0.5) { + return floor(x); + } else if ((x - base) > 0.5) { + return ceil(x); + } else { + if (mod(base, 2.0) == 0.0) { + return base; + } else { + return base + 1.0; + } + } +`,f7=Ae({opSnippet:p7}),m7={kernelName:pi,backendName:"webgl",kernelFunc:f7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const g7="return inversesqrt(x);",y7=Ae({opSnippet:g7,cpuKernelImpl:Tj}),b7={kernelName:fi,backendName:"webgl",kernelFunc:y7};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class gy{constructor(e,t,s,r,o,a,i=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const u=Pe(o.length),c=Pe(a.length);let h="";s===1?h="i":s===2&&(h="i, j");const d=`getIndices(${h})`;let p="";r===1?p="i":r===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let g="";l&&(g="coords[0], coords[1]");const m=`getDefaultValue(${g})`,y=t>1?"strides[j]":"strides";this.userCode=` + ${u} strides = ${u}(${o}); + + void main() { + ${c} coords = getOutputCoords(); + float sum = 0.0; + bool found = false; + for (int i = 0; i < ${e}; i++) { + int flattenedIndex = 0; + for (int j = 0; j < ${t}; j++) { + int index = round(${d}); + flattenedIndex += index * ${y}; + } + if (flattenedIndex == coords[0]) { + sum += ${f}; + found = true; + } + } + setOutput(mix(${m}, sum, float(found))); + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class x7{constructor(e,t,s,r,o,a,i=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;const u=Pe(o.length),c=Pe(a.length);let h="";s===1?h="i":s===2&&(h="i, j");const d=`getIndices(${h})`;let p="";r===1?p="i":r===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let g="";l&&(g="coords[0], coords[1]");const m=`getDefaultValue(${g})`,y=t>1?"strides[j]":"strides",b=t>1?"strides[j + 1]":"strides";this.userCode=` + ${u} strides = ${u}(${o}); + + void main() { + ${c} coords = getOutputCoords(); + vec4 sum = vec4(0.); + vec4 found = vec4(0.); + for (int i = 0; i < ${e}; i+=2) { + ivec2 flattenedIndex = ivec2(0); + for (int j = 0; j < ${t}; j+=2) { + ivec4 index = round(${d}); + flattenedIndex += index.xz * ${y}; + if (j + 1 < ${t}) { + flattenedIndex += index.yw * ${b}; + } + } + if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] || + flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) { + vec4 updVals = ${f}; + if (flattenedIndex[0] == coords[0]) { + sum.xy += updVals.xy; + found.xy = vec2(1.); + } else if (flattenedIndex[0] == coords[0] + 1) { + sum.zw += updVals.xy; + found.zw = vec2(1.); + } + if (flattenedIndex[1] == coords[0]) { + sum.xy += updVals.zw; + found.xy = vec2(1.); + } else if (flattenedIndex[1] == coords[0] + 1) { + sum.zw += updVals.zw; + found.zw = vec2(1.); + } + } + } + setOutput(mix(${m}, sum, found)); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w7(n){const{inputs:e,backend:t,attrs:s}=n,{indices:r,updates:o}=e,{shape:a}=s,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=pr(o,r,a),d=[h/u,u];if(h===0)return t.makeTensorInfo(a,r.dtype);const p=se({inputs:{x:r},backend:t,attrs:{shape:[l,i]}}),f=se({inputs:{x:o},backend:t,attrs:{shape:[l,u]}}),g=t.makeTensorInfo([],"float32",new Float32Array([0]));let m;B().getBool("WEBGL_PACK")?m=new x7(l,i,p.shape.length,f.shape.length,c,d):m=new gy(l,i,p.shape.length,f.shape.length,c,d);const y=t.runWebGLProgram(m,[f,p,g],f.dtype),b=se({inputs:{x:y},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(g),b}const v7={kernelName:Dp,backendName:"webgl",kernelFunc:w7};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $7{constructor(e,t,s,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,s];const o="while (left < right) {",a=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=B().getNumber("WEBGL_VERSION")===2?o:a,l=r==="left"?"<":"<=";this.userCode=` + int findBound(int batch, float value) { + int left = 0; + int right = numInputs; + int mid; + ${i} + mid = (left + right) / 2; + if (getSortedSequence(batch, mid) ${l} value) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int valueIndex = coords[1]; + + float value = getValues(batch, valueIndex); + + setOutput(float(findBound(batch, value))); + } + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function S7(n){const{inputs:e,backend:t,attrs:s}=n,{sortedSequence:r,values:o}=e,{side:a}=s,i=new $7(r.shape[0],r.shape[1],o.shape[1],a),l=[[r.shape[1]]];return t.runWebGLProgram(i,[r,o],"int32",l)}const I7={kernelName:_p,backendName:"webgl",kernelFunc:S7};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class N7{constructor(e,t,s){this.variableNames=["c","a","b"],this.outputShape=t;let r,o;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)o="resRC",r="resRC";else{const i=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],u=[];for(let c=0;c= 1.0) { + setOutput(getA(${o})); + } else { + setOutput(getB(${o})); + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function C7(n){const{inputs:e,backend:t}=n,{condition:s,t:r,e:o}=e,a=new N7(s.shape.length,r.shape,r.shape.length);return t.runWebGLProgram(a,[s,r,o],an(r.dtype,o.dtype))}const k7={kernelName:rc,backendName:"webgl",kernelFunc:C7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const T7=` + // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. + // see: https://arxiv.org/abs/1706.02515 + float scaleAlpha = ${Hc}; + float scale = ${jc}; + return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); +`,E7=Ae({opSnippet:T7}),A7={kernelName:mi,backendName:"webgl",kernelFunc:E7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const R7=Yo+` + return 1.0 / (1.0 + exp(-1.0 * x)); +`,D7=` + vec4 result = 1.0 / (1.0 + exp(-1.0 * x)); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,O7=Ae({opSnippet:R7,packedOpSnippet:D7,cpuKernelImpl:Aj}),_7={kernelName:xi,backendName:"webgl",kernelFunc:O7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const F7=` + if (isnan(x)) { return 0.0; } + return sign(x); +`,L7=Ae({opSnippet:F7}),P7={kernelName:bi,backendName:"webgl",kernelFunc:L7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const z7=Yo+` + return sin(x); +`,M7=` + vec4 result = sin(x); + bvec4 isNaN = isnan(x); + ${oo} + return result; +`,B7=Ae({opSnippet:z7,packedOpSnippet:M7}),V7={kernelName:gi,backendName:"webgl",kernelFunc:B7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const W7=` + float e2x = exp(x); + return (e2x - 1.0 / e2x) / 2.0; +`,U7=Ae({opSnippet:W7}),G7={kernelName:yi,backendName:"webgl",kernelFunc:U7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const H7=` + float epsilon = 1.1920928955078125e-7; + float threshold = log(epsilon) + 2.0; + + bool too_large = x > -threshold; + bool too_small = x < threshold; + + float result; + float exp_x = exp(x); + + if (too_large){ + result = x; + } + else if (too_small){ + result = exp_x; + } + else{ + result = log(exp_x + 1.0); + } + return result; +`,j7=Ae({opSnippet:H7}),q7={kernelName:wi,backendName:"webgl",kernelFunc:j7};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const K7=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:o,paddings:a}=s;I(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const i=o.reduce((y,b)=>y*b),l=[[0,0]];l.push(...a);for(let y=1+o.length;yt.disposeIntermediateTensorInfo(y)),m},X7={kernelName:ic,backendName:"webgl",kernelFunc:K7};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Y7(n){const{inputs:e,backend:t}=n,{indices:s,values:r,denseShape:o,defaultValue:a}=e;if(o.shape.length!==1)throw new Error(`Dense shape must be a vector, saw: + ${o.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw: + ${s.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw: + ${r.shape}`);if(a.shape.length!==0)throw new Error(`Default value must be a scalar, saw: + ${a.shape}`);const i=t.readSync(s.dataId),l=t.readSync(r.dataId),u=t.readSync(o.dataId),c=t.readSync(a.dataId)[0],[h,d,p,f,g]=Dj(i,s.shape,s.dtype,l,r.dtype,u,c);return[t.makeTensorInfo(d,s.dtype,h),t.makeTensorInfo([d[0]],r.dtype,p),t.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(m=>Number(m)))),t.makeTensorInfo([g.length],s.dtype,new Int32Array(g))]}const Z7={kernelName:Fp,backendName:"webgl",kernelFunc:Y7};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function J7(n){const{inputs:e,backend:t}=n,{inputIndices:s,inputShape:r,newShape:o}=e;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(o.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${o.shape}`);const a=Array.from(t.readSync(r.dataId)),i=t.readSync(s.dataId),l=Array.from(t.readSync(o.dataId)),[u,c,h]=Oj(i,s.shape,s.dtype,a,l);return[t.makeTensorInfo(c,s.dtype,u),t.makeTensorInfo([h.length],o.dtype,new Int32Array(h))]}const Q7={kernelName:Lp,backendName:"webgl",kernelFunc:J7};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eZ(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:o}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(o.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${o.shape}`);const a=t.readSync(s.dataId),i=t.readSync(r.dataId),l=t.readSync(o.dataId),[u,c]=ES(a,s.shape,s.dtype,i,l,!0);return t.makeTensorInfo(c,s.dtype,u)}const tZ={kernelName:Pp,backendName:"webgl",kernelFunc:eZ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nZ(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:o}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(o.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${o.shape}`);const a=t.readSync(s.dataId),i=t.readSync(r.dataId),l=t.readSync(o.dataId),[u,c]=ES(a,s.shape,s.dtype,i,l);return t.makeTensorInfo(c,s.dtype,u)}const sZ={kernelName:zp,backendName:"webgl",kernelFunc:nZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rZ(n){const{inputs:e,backend:t,attrs:s}=n,{sparseIndices:r,sparseValues:o,defaultValue:a}=e,{outputShape:i}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:d}=pr(o,r,i),p=!1;if(o.dtype==="string"){const y=t.bufferSync(r),b=t.bufferSync(o),w=Ss(t.readSync(a.dataId)[0]),x=Ej(y,b,i,d,c,u,l,h,w,p);return t.makeTensorInfo(i,x.dtype,x.values)}const f=new gy(u,l,r.shape.length,o.shape.length,h,[d,1],p),g=t.runWebGLProgram(f,[o,r,a],o.dtype),m=se({inputs:{x:g},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(g),m}const oZ={kernelName:Mp,backendName:"webgl",kernelFunc:rZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aZ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{numOrSizeSplits:o,axis:a}=s,i=Se(a,r.shape)[0],l=cm(r,o,i),u=r.shape.length,c=new Array(u).fill(0),h=r.shape.slice();return l.map(d=>{const p=[...h];p[i]=d;const f=Zo({inputs:{x:r},backend:t,attrs:{begin:c,size:p}});return c[i]+=d,f})}const iZ={kernelName:lc,backendName:"webgl",kernelFunc:aZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ox="return sqrt(x);",lZ=Ae({opSnippet:ox,packedOpSnippet:ox,cpuKernelImpl:_j}),uZ={kernelName:vi,backendName:"webgl",kernelFunc:lZ};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cZ="return x * x;",hZ=Ae({opSnippet:cZ}),dZ={kernelName:Bp,backendName:"webgl",kernelFunc:hZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ax="return (a - b) * (a - b);",pZ=Ft({opSnippet:ax,packedOpSnippet:ax}),fZ={kernelName:$i,backendName:"webgl",kernelFunc:pZ};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mZ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e;if(r.dtype!=="string")throw new Error("Input must be of datatype string");const o=t.readSync(r.dataId),a=Ts(o),i=Fj(a,"string",s);return t.makeTensorInfo(r.shape,"string",i)}const gZ={kernelName:cc,backendName:"webgl",kernelFunc:mZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yZ({inputs:n,attrs:e,backend:t}){const{x:s}=n,r=_n+` + return x > 0.0 ? 1.0 : float(${e.alpha}); + `,o=new ts(s.shape,r);return t.runWebGLProgram(o,[s],s.dtype)}const bZ={kernelName:ki,backendName:"webgl",kernelFunc:yZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xZ{constructor(e,t,s){this.variableNames=["x"],this.outputShape=s;const r=s.length,o=Pe(s.length),a=Pe(s.length);let i="";if(r===1)i="coords * strides + begin";else{let l=0;i=s.map((u,c)=>(l++,s.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${l-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=` + ${o} begin = ${o}(${e}); + ${o} strides = ${o}(${t}); + + void main() { + ${a} coords = getOutputCoords(); + setOutput(getX(${i})); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wZ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:o,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=s,{finalShapeSparse:p,finalShape:f,isIdentity:g,sliceDim0:m,isSimpleSlice:y,begin:b,end:w,strides:x}=jf(r.shape,o,a,i,l,u,c,h,d);let $;if(g)$=se({inputs:{x:r},backend:t,attrs:{shape:f}});else if(m||y){I(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const E=Uf(b,w,x),A=Zo({inputs:{x:r},backend:t,attrs:{begin:b,size:E}});$=se({inputs:{x:A},backend:t,attrs:{shape:f}}),t.disposeIntermediateTensorInfo(A)}else if(t.shouldExecuteOnCPU([r])){const A=t.readSync(r.dataId),k=ve(r.shape,r.dtype,A),T=Lj(p,k,x,b);$=t.makeTensorInfo(f,r.dtype,T.values)}else{const A=new xZ(b,x,p);$=t.runWebGLProgram(A,[r],r.dtype)}const C=se({inputs:{x:$},backend:t,attrs:{shape:f}});return t.disposeIntermediateTensorInfo($),C}const vZ={kernelName:Vp,backendName:"webgl",kernelFunc:wZ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $Z(n){const{inputs:e,backend:t,attrs:s}=n,{separator:r,nGramWidths:o,leftPad:a,rightPad:i,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=e,d=t.readSync(c.dataId),p=t.readSync(h.dataId),[f,g]=Pj(d,p,r,o,a,i,l,u);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(h.shape,"int32",g)]}const SZ={kernelName:Wp,backendName:"webgl",kernelFunc:$Z};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IZ(n){const{inputs:e,backend:t,attrs:s}=n,{skipEmpty:r}=s,{input:o,delimiter:a}=e;if(o.dtype!=="string")throw new Error("Input must be of datatype string");if(o.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${o.shape}`);if(a.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);const i=t.readSync(o.dataId),l=t.readSync(a.dataId)[0],[u,c,h]=zj(i,l,r),d=c.length;return[t.makeTensorInfo([d,2],"int32",u),t.makeTensorInfo([d],"string",c),t.makeTensorInfo([2],"int32",new Int32Array(h))]}const NZ={kernelName:Up,backendName:"webgl",kernelFunc:IZ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function CZ(n){const{inputs:e,backend:t,attrs:s}=n,{numBuckets:r}=s,{input:o}=e;if(o.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const a=t.readSync(o.dataId),i=Mj(a,r);return t.makeTensorInfo(o.shape,"int32",i)}const kZ={kernelName:Gp,backendName:"webgl",kernelFunc:CZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TZ="return tan(x);",EZ=Ae({opSnippet:TZ}),AZ={kernelName:Ii,backendName:"webgl",kernelFunc:EZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RZ=` + float e2x = exp(-2.0 * abs(x)); + return sign(x) * (1.0 - e2x) / (1.0 + e2x); +`,DZ=Ae({opSnippet:RZ}),OZ={kernelName:Ni,backendName:"webgl",kernelFunc:DZ};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _Z(n){const{inputs:e,backend:t,attrs:s}=n,{tensor:r,indices:o,updates:a}=e,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=pr(a,o,r.shape),d=[h/u,u];if(h===0)return t.makeTensorInfo(r.shape,o.dtype);const p=se({inputs:{x:o},backend:t,attrs:{shape:[l,i]}}),f=se({inputs:{x:a},backend:t,attrs:{shape:[l,u]}}),g=se({inputs:{x:r},backend:t,attrs:{shape:d}}),m=new gy(l,i,p.shape.length,f.shape.length,c,d,!1,!0),y=t.runWebGLProgram(m,[f,p,g],g.dtype),b=se({inputs:{x:y},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(y),b}const FZ={kernelName:Op,backendName:"webgl",kernelFunc:_Z};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class LZ{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let a=0;a5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`imod(resRC, ${n[0]})`;const t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let r=0;r5){const l=t.readSync(r.dataId),u=r.dtype==="string"?l.map(d=>Ss(d)):l,c=ve(r.shape,r.dtype,u),h=Vj(c,o);return t.makeTensorInfo(h.shape,h.dtype,h.values)}const a=new LZ(r.shape,o);return t.runWebGLProgram(a,[r],r.dtype)}const zZ={kernelName:Ci,backendName:"webgl",kernelFunc:aI};class MZ{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int elemIdx = coords[1]; + + // We compare elements pair-wise within a group of size 2 * inc. + // The comparing rule for each group alternates between ascending + // and descending. Within each group, we compare each pair at + // positions i and i+inc. To decide whether an element at position i + // is x0 or x1, we mod it by 2 * inc, if the result is smaller than + // inc, it is in the first half of the group, we denote it as x0, + // otherwise we denote it as x1. + // For example, as shown in the Bitonic top K paper referenced above, + // Figure5(a) shows that element[1] is in the + // second half of the group when group size is 2, but it is in the + // first half of the group when group size is 4. + + bool isFirstInPair = imod(elemIdx, 2 * inc) < inc; + int i = isFirstInPair ? elemIdx : elemIdx - inc; + + int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); + int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc)); + float x0 = i0 < n ? getX(batch, i0) : negativeInf; + float x1 = i1 < n ? getX(batch, i1) : negativeInf; + + // Denotes which direction indices are in (ascending or descending). + bool reverse = imod(elemIdx, 2 * dir) >= dir; + bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0); + if (reverse == isGreater) { // Elements in opposite order of direction + int iTemp = i0; + i0 = i1; + i1 = iTemp; + } + if (isFirstInPair) { + setOutput(float(i0)); + } else { + setOutput(float(i1)); + } + } + `}}class BZ{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=` + void main() { + // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ... + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int elemIdx = coords[1]; + + // The output size is half of the previous size. + // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4), + // we only need to output the indices at positions |, the indices at + // positions _ can be thrown away, see Figure5(b) After Phase 2 + // (Merge phase) in the Bitonic Top K paper referenced above. + // For example, the paper shows we only need to output the orange bars. + // The output sequence should look like this | | | | | | | |. + // Because the sequence is halved, to map the output index back + // to the previous sequence to find the corresponding value, + // we need to double the index. When we double the index, + // we basically interpolate a position, so 2i looks like + // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position + // of each 2k positions by - elemIdx % k. E.g. for output at + // index 4,5,6,7, we want to get the corresponding element at + // original index 8,9,10,11, for output at index 8,9,10,11, + // we want to get the corresponding element at original index + // 16,17,18,19, so on and so forth. + + int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k)); + int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); + int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k)); + + float x0 = getX(batch, i0); + float x1 = i1 < n ? getX(batch, i1) : x0; + + setOutput(x0 >= x1 ? float(i0) : float(i1)); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xr(n,e){e!==null&&n.disposeIntermediateTensorInfo(e)}function ix(n){let e=1;for(;el){const T=t.readSync(r.dataId),[S,_]=Wj(T,u,r.dtype,o,a);return[t.makeTensorInfo(S.shape,S.dtype,S.values),t.makeTensorInfo(_.shape,_.dtype,_.values)]}if(o===0)return u[u.length-1]=0,[t.makeTensorInfo(u,r.dtype,[]),t.makeTensorInfo(u,"int32",[])];if(c===1)return[r,Qi({attrs:{shape:u,dtype:"int32",value:0},backend:t})];const h=t.texData.get(r.dataId),d=h!==null&&h.isPacked,p=d?t.unpackTensor(r):r,g=G(u)/c,m=se({inputs:{x:p},attrs:{shape:[g,c]},backend:t});d&&xr(t,p);const y=ix(o),b=ix(c);let w=null;const x=()=>w===null?[m,m]:[m,w],$=(T,S,_)=>{const P=x(),V=new MZ(_),W=[[c],[w===null?1:0],[Number.NEGATIVE_INFINITY],[T],[S]],j=w;w=t.runWebGLProgram(V,P,"int32",W),xr(t,j)};for(let T=1;T=1;_/=2)$(S,_,[g,b])}for(let T=b;T>y;T/=2){const S=x(),_=new BZ([g,T/2]),V=[[c],[w===null?1:0],[y]],M=w;w=t.runWebGLProgram(_,S,"int32",V),xr(t,M);const W=y/2,j=W*2;for(let U=W;U>=1;U/=2)$(j,U,w.shape)}let C=w;w=Zo({inputs:{x:w},backend:t,attrs:{begin:0,size:[g,o]}}),xr(t,C);let E=JS({inputs:{x:m,indices:w},backend:t,attrs:{axis:1,batchDims:1}});xr(t,m);const A=u.slice(0,-1);A.push(o),C=w,w=se({inputs:{x:w},attrs:{shape:A},backend:t}),xr(t,C);const k=E;return E=se({inputs:{x:E},attrs:{shape:A},backend:t}),xr(t,k),[E,w]}const WZ={kernelName:Hp,backendName:"webgl",kernelFunc:VZ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class UZ{constructor(e,t,s,r,o,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i=s==="nearest"?1:2;let l;switch(r){case"constant":l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4;break;default:l=1;break}this.userCode=` + float mapCoord(float outCoord, float len) { + float inCoord = outCoord; + if(${l} == 2) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + if (inCoord < sz2) { + inCoord = sz2 * float(int(float(-inCoord / sz2))) + + inCoord; + } + inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0; + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + inCoord -= sz2 * float(int(float(inCoord / sz2))); + if (inCoord >= len) { + inCoord = sz2 - inCoord - 1.0; + } + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${l} == 3) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord += len * (float(int(float(-inCoord / sz))) + 1.0); + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord -= len * float(int(float(inCoord / sz))); + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${l} == 4) { + return clamp(outCoord, 0.0, len - 1.0); + } else { + return outCoord; + } + } + + float readWithFillValue(int batch, int coordY, int coordX, + int channel) { + float outputValue; + if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) { + outputValue = getImage(batch, coordY, coordX, channel); + } else { + outputValue = float(${o}); + } + return outputValue; + } + + void main() { + ivec4 coords = getOutputCoords(); + float outputValue; + int batch = coords[0]; + int x = coords[2]; + int y = coords[1]; + int channel = coords[3]; + float xf = float(x); + float yf = float(y); + float a1 = getTransforms(batch, 0); + float a2 = getTransforms(batch, 1); + float a3 = getTransforms(batch, 2); + float b1 = getTransforms(batch, 3); + float b2 = getTransforms(batch, 4); + float b3 = getTransforms(batch, 5); + float c1 = getTransforms(batch, 6); + float c2 = getTransforms(batch, 7); + float projection = c1 * xf + c2 * yf + 1.0; + if (projection == 0.0) { + outputValue = float(${o}); + } else { + float inX = (a1 * xf + a2 * yf + a3) / projection; + float inY = (b1 * xf + b2 * yf + b3) / projection; + float mapX = mapCoord(inX, float(${t})); + float mapY = mapCoord(inY, float(${e})); + + if (${i} == 1) { + int coordY = int(round(mapY)); + int coordX = int(round(mapX)); + outputValue = readWithFillValue(batch, coordY, coordX, + channel); + } else { + float yFloor = floor(mapY); + float xFloor = floor(mapX); + float yCeil = yFloor + 1.0; + float xCeil = xFloor + 1.0; + float valueYFloor = (xCeil - mapX) * + readWithFillValue(batch, int(yFloor), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yFloor), int(xCeil), channel); + float valueYCeil = (xCeil - mapX) * + readWithFillValue(batch, int(yCeil), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yCeil), int(xCeil), channel); + outputValue = (yCeil - mapY) * valueYFloor + + (mapY - yFloor) * valueYCeil; + } + } + setOutput(outputValue); + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GZ(n){const{inputs:e,backend:t,attrs:s}=n,{image:r,transforms:o}=e,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=s,[c,h,d,p]=r.shape,[f,g]=u??[h,d],m=[c,f,g,p],y=new UZ(h,d,a,i,l,m);return t.runWebGLProgram(y,[r,o],"float32")}const HZ={kernelName:jp,backendName:"webgl",kernelFunc:GZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jZ(n){const{inputs:e,attrs:t,backend:s}=n,{axis:r}=t,{x:o}=e;Go(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(o.dataId),{outputValues:i,outputShape:l,indices:u}=Uj(a,r,o.shape,o.dtype);return[s.makeTensorInfo(l,o.dtype,i),s.makeTensorInfo([u.length],"int32",u)]}const qZ={kernelName:qp,backendName:"webgl",kernelFunc:jZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KZ(n){const{inputs:e,backend:t,attrs:s}=n,{value:r}=e;let{axis:o}=s;o<0&&(o+=r.shape.length);const a=r,i=a.shape.length,l=r.shape[o],u=new Array(i-1);let c=0;for(let g=0;gt.disposeIntermediateTensorInfo(g)),f}const XZ={kernelName:hc,backendName:"webgl",kernelFunc:KZ};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class YZ{constructor(e,t){this.variableNames=["x","segmentIds"];const s=e.windowSize,r=e.batchSize,o=e.inSize,a=e.numSegments,i=a*Math.ceil(o/s);this.outputShape=[r,i];const l="0.0",u="sumValue",c=Math.floor(s/4)*4,h=s%4,d=` + sumValue += dot(values, segFilter); + `;let p="";o%s>0&&(p=` + if (inIdx < 0 || inIdx >= ${o}) { + return initializationValue; + } + `);let f="";o%s>0&&(f=` + if (inIdx < 0 || inIdx >= ${o}) { + return -1.0; + } + `),this.userCode=` + const float initializationValue = ${l}; + + float getValue(int batch, int inIdx) { + ${p} + return getX(batch, inIdx); + } + + float getSegmentIdAtIndex(int inIdx) { + ${f} + return getSegmentIds(inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = int(floor(float(outIdx) / float( + ${a})) * float(${s})); + int currentSeg = int(mod(float(outIdx), float(${a}))); + + float sumValue = 0.0; + + for (int i = 0; i < ${c}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 + ); + + ${d} + } + + int inIdx = inOffset + ${c}; + if (${h===1}) { + vec4 values = vec4( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + int inIdxSeg = int(getSegmentIdAtIndex(inIdx)); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + 0, + 0, + 0 + ); + + ${d} + } else if (${h===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + 0, + 0 + ); + + ${d} + } else if (${h===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + 0 + ); + + ${d} + } + setOutput(${u}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZZ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,segmentIds:o}=e,{numSegments:a}=s,i=r.shape.length,l=[];let u=0;const c=Je([u],i);let h=r;c!=null&&(h=Ut({inputs:{x:r},backend:t,attrs:{perm:c}}),l.push(h),u=st(1,i)[0]);const d=Y0(h.shape,u,a),p=G([h.shape[u]]),f=se({inputs:{x:h},backend:t,attrs:{shape:[-1,p]}});l.push(f);const g=Zp(r.dtype),m=(x,$,C,E,A)=>{const k=x.shape[0],T=x.shape[1],S=X0(T,A),_={windowSize:S,inSize:T,batchSize:k,numSegments:A},P=new YZ(_,$),V=t.compileAndRun(P,[x,C],E);if(l.push(V),V.shape[1]===A)return V;const M=oI({backend:t,attrs:{start:0,stop:A,step:1,dtype:"float32"}}),W=aI({inputs:{x:M},backend:t,attrs:{reps:[T/S]}});return l.push(M),l.push(W),m(V,$,W,E,A)},y=m(f,"unsortedSegmentSum",o,g,a),b=se({inputs:{x:y},backend:t,attrs:{shape:d}});let w=b;if(c!=null){l.push(b);const x=cr(c);w=Ut({inputs:{x:w},backend:t,attrs:{perm:x}})}return l.forEach(x=>t.disposeIntermediateTensorInfo(x)),w}const JZ={kernelName:dc,backendName:"webgl",kernelFunc:ZZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QZ=[Lq,zq,Vq,Gq,jq,Xq,Zq,Qq,sK,oK,lK,hK,fK,bK,vK,SK,NK,EK,RK,OK,PK,GK,jK,YK,JK,r6,a6,c6,xq,p6,b6,$6,T6,R6,O6,F6,P6,V6,G6,q6,X6,Z6,Q6,nX,rX,lX,cX,pX,gX,bX,$X,CX,AX,OX,LX,PX,MX,VX,UX,HX,qX,ZX,e5,s5,o5,l5,h5,m5,x5,bq,v5,g6,I5,k5,A5,vq,_5,z5,B5,G5,q5,Z5,e8,r8,l8,h8,p8,y8,x8,v8,N8,k8,E8,R8,O8,P8,V8,H8,Q8,Iq,sY,aY,uY,dY,e6,mY,yY,xY,$Y,CY,Sq,TY,AY,DY,_Y,FY,t6,X8,zY,WY,jY,Cq,YY,QY,s7,a7,c7,d7,m7,b7,v7,I7,k7,A7,_7,P7,V7,G7,WK,Z8,q7,X7,Z7,Q7,tZ,sZ,oZ,iZ,uZ,dZ,fZ,gZ,bZ,vZ,SZ,NZ,kZ,Y8,Oq,AZ,OZ,FZ,zZ,WZ,HZ,_q,qZ,XZ,JZ,gY];for(const n of QZ)Xp(n);/** @license See the LICENSE file. */const eJ="4.22.0";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const i9={"tfjs-core":XR,"tfjs-backend-cpu":kB,"tfjs-backend-webgl":gq,"tfjs-data":Nv,"tfjs-layers":Om,"tfjs-converter":Rz,tfjs:eJ};export{hu as Abs,Oa as Acos,_a as Acosh,s0 as AdadeltaOptimizer,r0 as AdagradOptimizer,o0 as AdamOptimizer,a0 as AdamaxOptimizer,Ro as Add,du as AddN,Gd as All,Hd as Any,pu as ArgMax,fu as ArgMin,Fa as Asin,La as Asinh,Pa as Atan,Ma as Atan2,za as Atanh,mu as AvgPool,gu as AvgPool3D,qd as AvgPool3DGrad,jd as AvgPoolGrad,yu as BatchMatMul,bu as BatchToSpaceND,Kd as Bincount,xu as BitwiseAnd,Xd as BroadcastArgs,NI as BroadcastTo,n3 as Callback,cF as CallbackList,Ba as Cast,Va as Ceil,Wa as ClipByValue,Yd as Complex,wu as ComplexAbs,vu as Concat,$u as Conv2D,Zd as Conv2DBackpropFilter,Su as Conv2DBackpropInput,Iu as Conv3D,Jd as Conv3DBackpropFilterV2,Qd as Conv3DBackpropInputV2,Ua as Cos,Ga as Cosh,tp as CropAndResize,ep as Cumprod,Nu as Cumsum,pF as CustomCallback,lx as DataStorage,np as DenseBincount,sp as DepthToSpace,Cu as DepthwiseConv2dNative,rp as DepthwiseConv2dNativeBackpropFilter,op as DepthwiseConv2dNativeBackpropInput,ap as Diag,ku as Dilation2D,Wh as Dilation2DBackpropFilter,Vh as Dilation2DBackpropInput,ip as Draw,yx as ENV,s3 as EarlyStopping,lp as Einsum,ja as Elu,up as EluGrad,xI as Environment,Tu as Equal,qa as Erf,Ka as Exp,Eu as ExpandDims,Xa as Expm1,cp as FFT,hp as Fill,dp as FlipLeftRight,Ya as Floor,Za as FloorDiv,Uh as FromPixels,Au as FusedBatchNorm,Fl as FusedConv2D,Ll as FusedDepthwiseConv2D,zh as GPGPUContext,pp as GatherNd,Ru as GatherV2,uv as GraphModel,Du as Greater,Ja as GreaterEqual,dF as History,fp as IFFT,Qa as Identity,mp as Imag,dt as InputSpec,ei as IsFinite,ti as IsInf,ni as IsNan,zd as KernelBackend,Mu as LRN,yp as LRNGrad,A_ as LayerVariable,Xs as LayersModel,Ou as LeakyRelu,_u as Less,Fu as LessEqual,gp as LinSpace,si as Log,ri as Log1p,CI as LogSoftmax,Lu as LogicalAnd,Pu as LogicalNot,zu as LogicalOr,tJ as LogicalXor,nJ as LowerBound,ph as MathBackendCPU,gh as MathBackendWebGL,sJ as MatrixBandPart,Bu as Max,Vu as MaxPool,Wu as MaxPool3D,xp as MaxPool3DGrad,bp as MaxPoolGrad,wp as MaxPoolWithArgmax,oi as Maximum,Uu as Mean,Gu as Min,ai as Minimum,Hu as MirrorPad,ii as Mod,i0 as MomentumOptimizer,vp as Multinomial,li as Multiply,ju as Neg,$p as NonMaxSuppressionV3,Sp as NonMaxSuppressionV4,Ip as NonMaxSuppressionV5,qu as NotEqual,Ox as OP_SCOPE_SUFFIX,Xu as OneHot,Ku as OnesLike,fr as Optimizer,YR as OptimizerConstructors,Yu as Pack,Zu as PadV2,rJ as Pool,ui as Pow,Ju as Prelu,Qu as Prod,l0 as RMSPropOptimizer,ds as RNN,Np as RaggedGather,Cp as RaggedRange,kp as RaggedTensorToTensor,Tp as Range,$y as Rank,Ep as Real,Ha as RealDiv,ci as Reciprocal,qt as Reduction,hi as Relu,di as Relu6,ec as Reshape,nc as ResizeBilinear,Rp as ResizeBilinearGrad,tc as ResizeNearestNeighbor,Ap as ResizeNearestNeighborGrad,sc as Reverse,Kp as RotateWithOffset,pi as Round,fi as Rsqrt,Mf as SGDOptimizer,Dp as ScatterNd,_p as SearchSorted,rc as Select,mi as Selu,Co as Sequential,xi as Sigmoid,bi as Sign,gi as Sin,yi as Sinh,oc as Slice,uc as Softmax,wi as Softplus,ic as SpaceToBatchND,Fp as SparseFillEmptyRows,Lp as SparseReshape,Pp as SparseSegmentMean,zp as SparseSegmentSum,Mp as SparseToDense,lc as SplitV,vi as Sqrt,Bp as Square,$i as SquaredDifference,cc as StaticRegexReplace,ki as Step,Vp as StridedSlice,Wp as StringNGrams,Up as StringSplit,Gp as StringToHashBucketFast,Si as Sub,ac as Sum,us as SymbolicTensor,Ii as Tan,Ni as Tanh,Re as Tensor,pt as TensorBuffer,Op as TensorScatterUpdate,Ci as Tile,Hp as TopK,jp as Transform,fo as Transpose,qp as Unique,hc as Unpack,dc as UnsortedSegmentSum,oJ as UpperBound,zl as Variable,pc as ZerosLike,_l as _FusedMatMul,lt as abs,Yx as acos,Zx as acosh,Y as add,WN as addN,of as all,Bl as any,vo as argMax,Jx as argMin,Qx as asin,ew as asinh,tw as atan,nw as atan2,sw as atanh,mc as avgPool,rw as avgPool3d,Fx as backend,tD as backend_util,hC as basicLSTMCell,Ri as batchNorm,ow as batchNorm2d,aw as batchNorm3d,iw as batchNorm4d,gc as batchToSpaceND,lw as bincount,wC as bitwiseAnd,pE as booleanMaskAsync,$C as broadcastArgs,yo as broadcastTo,NJ as broadcast_util,_J as browser,ve as buffer,JJ as callbacks,ee as cast,uw as ceil,ln as clipByValue,vs as clone,Js as complex,at as concat,cw as concat1d,hw as concat2d,dw as concat3d,pw as concat4d,PJ as constraints,lf as conv1d,tr as conv2d,cf as conv2dTranspose,fw as conv3d,gw as conv3dTranspose,lJ as copyRegisteredKernels,yc as cos,hf as cosh,Lf as cosineWindow,Vl as cumprod,df as cumsum,Cs as customGrad,s9 as data,nd as denseBincount,mJ as deprecationWarn,yw as depthToSpace,Di as depthwiseConv2d,e9 as deregisterOp,hJ as device_util,HC as diag,bw as dilation2d,fJ as disableDeprecationWarnings,be as dispose,gJ as disposeVariables,ce as div,xw as divNoNan,ww as dot,qw as dropout,po as einsum,Oi as elu,pJ as enableDebugMode,dJ as enableProdMode,Kw as enclosingPowerOfTwo,Yn as engine,tk as ensureShape,B as env,wn as equal,pf as erf,Sw as euclideanNorm,un as exp,Lt as expandDims,Iw as expm1,mf as eye,Rc as fft,Do as fill,$J as findBackend,SJ as findBackendFactory,Fi as floor,rf as floorDiv,yq as forceHalfFloat,FE as fused,Li as gather,SE as gatherND,FJ as gather_util,tN as getBackend,by as getGradient,Pl as getKernel,Gh as getKernelsForBackend,o9 as gpgpu_util,CJ as grad,kJ as grads,Jt as greater,hr as greaterEqual,Ia as ifft,bc as imag,Bn as image,kE as inTopKAsync,zJ as initializers,sL as input,m0 as io,Rf as irfft,Nw as isFinite,Cw as isInf,kw as isNaN,bt as keep,LJ as kernel_impls,KJ as layers,xc as leakyRelu,wa as less,Yr as lessEqual,n0 as linalg,kk as linspace,t9 as loadGraphModel,n9 as loadGraphModelSync,MJ as loadLayersModel,Tw as localResponseNormalization,vn as log,wc as log1p,Ew as logSigmoid,gf as logSoftmax,$c as logSumExp,Gn as logicalAnd,Sc as logicalNot,yf as logicalOr,Aw as logicalXor,dR as losses,Uk as lowerBound,Ne as matMul,OJ as math,En as max,Ic as maxPool,Rw as maxPool3d,qk as maxPoolWithArgmax,Os as maximum,et as mean,Ny as memory,Yk as meshgrid,XJ as metrics,xa as min,zr as minimum,Dw as mirrorPad,Ow as mod,BJ as model,YJ as models,Nc as moments,gE as movingAverage,O as mul,nT as multiRNNCell,rT as multinomial,Ge as neg,k0 as nextFrame,_i as norm,$o as notEqual,va as oneHot,rn as ones,$n as onesLike,D as op,uT as outerProduct,dr as pad,dT as pad1d,fT as pad2d,gT as pad3d,bT as pad4d,_w as pool,Ns as pow,kc as prelu,Xx as print,Fw as prod,yJ as profile,CT as raggedGather,TT as raggedRange,AT as raggedTensorToTensor,DT as rand,u2 as randomGamma,$f as randomNormal,d2 as randomStandardNormal,Zr as randomUniform,m2 as randomUniformInt,So as range,wJ as ready,$a as real,zw as reciprocal,_x as registerBackend,WJ as registerCallbackConstructor,TI as registerGradient,Xp as registerKernel,QJ as registerOp,ZJ as regularizers,hs as relu,Sf as relu6,vJ as removeBackend,F as reshape,An as reverse,$2 as reverse1d,I2 as reverse2d,C2 as reverse3d,T2 as reverse4d,Dc as rfft,If as round,Nf as rsqrt,pe as scalar,bE as scatterND,RJ as scatter_util,bf as searchSorted,Cf as selu,kf as separableConv2d,VJ as sequential,DJ as serialization,xJ as setBackend,IJ as setPlatform,GG as setWebGLContext,_2 as setdiff1dAsync,CB as shared,ss as sigmoid,Mw as sign,hR as signal,Tf as sin,Ef as sinh,Te as slice,Tc as slice1d,Af as slice2d,Ec as slice3d,Sa as slice4d,KR as slice_util,Ac as softmax,Oo as softplus,Cc as spaceToBatchND,pR as sparse,vE as sparseToDense,cR as spectral,on as split,At as sqrt,ze as square,Df as squaredDifference,Jr as squeeze,Xt as stack,Fo as step,Bw as stridedSlice,fR as string,ae as sub,ie as sum,Zp as sumOutType,Vw as tan,Lr as tanh,xn as tensor,Pt as tensor1d,Tr as tensor2d,Ww as tensor3d,eE as tensor4d,tE as tensor5d,nE as tensor6d,rE as tensorScatterUpdate,cJ as tensor_util,AJ as test_util,z as tidy,kn as tile,bJ as time,Uw as topk,io as train,ke as transpose,_f as truncatedNormal,Gw as unique,iJ as unregisterGradient,aJ as unregisterKernel,Ff as unsortedSegmentSum,Rn as unstack,an as upcastType,cE as upperBound,uJ as util,TJ as valueAndGrad,EJ as valueAndGrads,Hw as variable,Rk as variableGrads,i9 as version,Rz as version_converter,XR as version_core,kB as version_cpu,Om as version_layers,gq as version_webgl,a9 as webgl,r9 as webgl_util,Tt as where,jw as whereAsync,ct as zeros,Ee as zerosLike}; diff --git a/templates/js_translations.html b/templates/js_translations.html index eb6f277..8c2e3b3 100644 --- a/templates/js_translations.html +++ b/templates/js_translations.html @@ -45,6 +45,18 @@ window.BOOMCAST_I18N = { finished: "{% trans 'Finished' as value %}{{ value|escapejs }}", buffering: "{% trans 'Buffering…' as value %}{{ value|escapejs }}", couldNotLoad: "{% trans 'Could not load this recording.' as value %}{{ value|escapejs }}", + checkingRecording: "{% trans 'Checking recording…' as value %}{{ value|escapejs }}", + readyToSubmit: "{% trans 'Ready to submit.' as value %}{{ value|escapejs }}", + extractingAudio: "{% trans 'Extracting audio from video…' as value %}{{ value|escapejs }}", + videoExtractionFailed: "{% trans 'Could not extract audio from this video. Please choose an audio recording.' as value %}{{ value|escapejs }}", + preparationCancelled: "{% trans 'Preparation cancelled. Choose a recording to continue.' as value %}{{ value|escapejs }}", + videoAudioOnly: "{% trans 'Video processed on this device. Only extracted audio will be sent if you submit.' as value %}{{ value|escapejs }}", + speechGateTitle: "{% trans 'This recording appears to contain speech, but no relevant sound was detected.' as value %}{{ value|escapejs }}", + speechGateMessage: "{% trans 'To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review.' as value %}{{ value|escapejs }}", + irrelevantGateTitle: "{% trans 'No relevant sound was detected.' as value %}{{ value|escapejs }}", + irrelevantGateMessage: "{% trans 'BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review.' as value %}{{ value|escapejs }}", + gateChooseMessage: "{% trans 'Recording checked. Choose another recording or submit for manual review.' as value %}{{ value|escapejs }}", + secureVideoFailed: "{% trans 'Could not prepare this video for upload. Please choose an audio recording.' as value %}{{ value|escapejs }}", manualReport: "{% trans 'Manual report' as value %}{{ value|escapejs }}" };